Java Swing-通过其他方法设置Jlabel文本 [英] Java Swing - set Jlabel text from another method

查看:93
本文介绍了Java Swing-通过其他方法设置Jlabel文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Java和Swing还是很陌生,我正在使用Windowbuilder来尝试一些我想到的GUI想法,但是在尝试设置Jlabel的文本时遇到了问题.

I'm pretty new to Java and Swing, and I'm using Windowbuilder to play around with a few GUI ideas I have, but I've run into a problem when trying to set the text of a Jlabel.

Windowbuilder已在initialize()方法中自动创建了Jlabel的实例,称为pathLabel,如下所示:

Windowbuilder has automatically created an instance of the Jlabel, called pathLabel, in the initialize() method like so:

private void initialize() {
    frame = new JFrame();
    frame.setBounds(100, 100, 570, 393);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);

    JLabel pathLabel = new JLabel("New label");
    pathLabel.setBounds(61, 296, 414, 15);
    frame.getContentPane().add(pathLabel);}

如果我从initialize()方法中使用pathLabel.setText(在此处输入文本"),则可以正常工作,但是如何从完全不同的方法中设置文本?这不是让我引用它.

If I use pathLabel.setText("enter text here") from within this initialize() method, then it works fine, but how can I set text from a completely different method? It's not letting me reference it.

我在C#的Visual Studio中从未遇到此问题,并且能够通过我选择的任何方法设置标签的文本.我想念什么?

I never had this problem in Visual Studio with C#, and was able to set the text of a label from any method I choose. What am I missing?

我希望这是有道理的,非常感谢您的帮助.谢谢.

I hope this makes sense, and I appreciate any help at all. Thanks.

推荐答案

您可以将pathLabel作为实例变量放入您的类中,并通过该类中的所有方法对其进行访问.

You can put pathLabel as a instance variable in your class and access it across all the methods in the class.

class GUIClass extends JFrame{
 JLabel pathLabel;
 private void initialize() {
   frame = new JFrame();
   frame.setBounds(100, 100, 570, 393);
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.getContentPane().setLayout(null);

   pathLabel = new JLabel("New label");
   pathLabel.setBounds(61, 296, 414, 15);
   frame.getContentPane().add(pathLabel);
}
void func(){
   pathLabel.setText("enter text here");
}

这篇关于Java Swing-通过其他方法设置Jlabel文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆