我在更新方法中的 jlabel 时遇到问题。这是我的代码:
JLabel curStatus = new JLabel("");
JButton jbtnSubmit;
public static void main(String[] args) {
test gui = new test();
gui.startGUI();
// gui.setCurStatus("testing!"); << seems to work here,
//but when i call it from another class, it doesn't want to run.
}
// Set up the GUI end for the user
public void startGUI() {
// These are all essential GUI pieces
new JTextArea("");
final JFrame jfrm = new JFrame("my program");
jfrm.setLayout(new FlowLayout());
jfrm.setSize(300, 300);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jbtnSubmit = new JButton("Submit");
jfrm.add(jbtnSubmit);
jfrm.add(curStatus);
jfrm.setVisible(true);
}
public void setCurStatus(String inCurStatus) {
curStatus.setText(inCurStatus);
curStatus.setVisible(true);
}
发生的情况是标签 curStatus 没有出现。例如,这是一个调用:
gui1.setCurStatus("Now running diagnostics... Please wait!");
最佳答案
您的问题似乎是错误引用之一。
以下是创建 GUI 的方法:
public static void main(String[] args) {
test gui = new test();
gui.startGUI();
// gui.setCurStatus("testing!"); << seems to work here,
// but when i call it from another class, it doesn't want to run.
}
您在主方法内创建“测试”对象(应命名为“Test”以符合 Java 命名约定)。由于它是在 main 内部声明的,因此该变量仅在 main 内部具有作用域,并且在其他地方都可见。
然后您告诉我们您正在像这样调用该方法:
gui1.setCurStatus("Now running diagnostics... Please wait!");
gui1 变量引用一个测试类对象,但它可能引用与正在显示的测试对象不同的对象,因为原始显示的测试对象仅由本地变量引用主要方法。
要解决此问题,您必须确保对当前显示的测试对象调用 setCurStatus。如何执行此操作取决于您的其余代码,尽管我们要求您这样做,但您拒绝向我们展示这些代码。
编辑:根据您发布的最新代码(由于缺少方法createTasksFile()
,它仍然无法为我编译,我的假设是正确,您正在对不是显示对象的 gui 对象调用 setCurStatus(...)
:
public static String[] runDiagnostics() throws IOException {
gui gui1 = new gui(); // (A)
gui1.setCurStatus("Now running diagnostics... Please wait!");
在第 (A) 行中,您创建了一个新的 gui 对象并对其调用 setCurStatus,但它不是正在显示的 GUI 对象,而是一个完全不同且不相关的对象。它唯一的关系是它是与所显示的对象属于同一类的对象,但仅此而已。解决方案是获取对显示的 GUI 的引用,并仅在该对象上调用此方法。
此外,Robin 的假设是正确的,因为即使您解决了这个问题,您也会遇到 Swing 并发问题。 JLabel 不会更新,因为 Swing 线程正在尝试打开文件:
public static String[] runDiagnostics() throws IOException {
gui gui1 = new gui();
gui1.setCurStatus("Now running diagnostics... Please wait!");
int i = 0;
int errorsI = 0;
File f = new File("tasks.txt");
String[] errors = { "", "", "", "", "" };
// try to create the file three times
do {
f.createNewFile();
i++;
} while (!f.exists() && i < 3);
所以我们都是对的。解决方案是在后台线程上打开文件,SwingWorker 在这里可以很好地工作。
编辑2
因此,要解决引用问题,请使用 gui 参数将 gui 的引用传递到 runDiagnostics 方法中。然后对此参数调用 setCurStatus 方法。例如:
public static String[] runDiagnostics(gui gui1) throws IOException {
//!! gui gui1 = new gui(); // !! no longer needed
gui1.setCurStatus("Now running diagnostics... Please wait!");
调用该方法时,您必须传入 GUI:
//!! results = taskBckg.runDiagnostics();
results = taskBckg.runDiagnostics(gui);
此外,请编辑您的所有代码,使其遵循 Java 命名约定。所有类名都应以大写字母开头。这使得其他人更容易理解您的代码在做什么。
关于java - 更新 jlabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9046175/