更新jLabel

问题描述 投票:1回答:1

我有一个简单的GUI,其中包含一个jTextField,它等待用户放入内容。单击按钮后,程序:

  1. 读取输入,将其保存在String变量中;
  2. 打开一个新的GUI(在单独的类文件中),该GUI包含一个空的jLabel,并将String变量传递给它,从而将jLabel文本更改为它。

问题是,无论我多么努力地重新配置代码,添加诸如repaint(),revalidate()等之类的东西,第二个GUI中的jLabel都保持为空。使用System.out.println(jLabel.getText())显示文本值确实已更改,但未显示。如何“刷新”此jLabel,以便显示我想要的内容?我知道我可以添加一个事件,尽管我不希望用户单击任何东西来刷新GUI,但启动时值应该在那里。我已经阅读了几篇类似的文章,但发现这些解决方案对我不起作用。

第一个GUI的按钮单击事件的代码:

private void sbuttonActionPerformed(java.awt.event.ActionEvent evt) {                                        
    errortext.setText("");
    Search = sfield.getText();
    Transl = hashes.find(Search);
    if (Transl.equals("0")) errortext.setText("Word not found in database.");
    else {
        ws.run(Search, Transl); // <- this opens the second GUI, with two String parameters I want to display in the second GUI;
    }
}

第二个GUI的代码(活动单词和翻译是给我带来麻烦的jLabel。):

public void run(String Search, String Transl) {
    WordScreen init = new WordScreen(); //initialise the second GUI;
    init.setVisible(true);
    activeword.setText(Search); 
    translation.setText(Transl);
}

任何回复都非常欢迎!如果需要,请询问我有关代码的更多信息,我将确保尽快答复!

java swing refresh jlabel
1个回答
0
投票

最佳解决方案:更改WordScreen的构造函数以接受两个感兴趣的字符串:

来自此:

public void run(String Search, String Transl) {
    WordScreen init = new WordScreen(); //initialise the second GUI;
    init.setVisible(true);
    activeword.setText(Search); 
    translation.setText(Transl);
}

至此:

public void run(String search, String transl) {
    WordScreen init = new WordScreen(search, transl); 
    init.setVisible(true);
}

然后在WordScreen构造函数中在需要的地方使用这些字符串:

public WordScreen(String search, String transl) {
    JLabel someLabel = new JLabel(search);
    JLabel otherLabel = new JLabel(transl);

    // put them where needed
}

请注意,如果您不发布体面的MRE,我将无法创建全面的答案>


顺便说一句,您将要学习和使用Java naming conventions。变量名都应以小写字母开头,而类名应以大写字母开头。学习和遵循此规则将使我们能够更好地理解您的代码,并使您能够更好地理解其他人的代码。

© www.soinside.com 2019 - 2024. All rights reserved.