开发者社区> 问答> 正文

更新jLabel

我有一个简单的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);
}

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

问题来源:Stack Overflow

展开
收起
montos 2020-03-25 23:34:14 411 0
1 条回答
写回答
取消 提交回答
  • 最佳解决方案:更改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命名约定。变量名都应以小写字母开头,而类名应以大写字母开头。学习和遵循此规则将使我们能够更好地理解您的代码,并使您能够更好地理解其他人的代码。

    回答来源:Stack Overflow

    2020-03-25 23:35:18
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载