不能在另一个类的秋千组件中设置值 [英] can't set values in swing components in another class
问题描述
我的UI上有此类
public class MyFrame extends JFrame{
JTextArea textArea;
public MyFrame(){
setSize(100,100);
textArea = new JTextArea(50,50);
Container content = getContentPane();
content.add(textArea);
}
public static void main(String[] args){
JFrame frame = new MyFrame();
frame.show();
UpdateText u = new UpdateText();
u.settext("Helloworld");
}
}
我还有另一个类,它将设置 textArea
的文本,在其中我扩展了MyFrame以访问另一个类中的textArea.
And I have this another class that will set the text of textArea
, in which I extended MyFrame to access textArea in another class.
public class UpdateText extends MyFrame{
public void settext(String msg){
textArea.setText(msg);
}
}
然后我实例化UpdateText并调用函数settext.但是文本似乎没有出现在GUI中.
Then I instantiate UpdateText and call the function settext. but the text doesn't seem to appear in the GUI.
推荐答案
首先,除非想要不同的行为,否则不要覆盖 setText()
方法.其次,您无需扩展任何内容.您所要做的就是按照这些简单的步骤进行操作,就可以了!
First of all, don't override the setText()
method unless you want different behavior. Second of all, you don't have to extend anything. All you have to do is follow these simple steps and you'll be set!
-
在
UpdateText
类中,将这些行放在其中:
In the
UpdateText
class, put these lines somewhere in it:
MyFrame gui;
public UpdateText(MyFrame in) {
gui = in;
}
在"MyFrame"类中,将此行放在开头:
In the 'MyFrame` class, put this line at the beginning:
UpdateText ut = new UpdateText(this);
现在,您可以通过使用 gui
进行更改来引用 UpdateText
类中 MyFrame
类中的所有内容.例如,假设您要更改文本区域的文本.代码如下:
Now, you can refer to everything in the MyFrame
class from the UpdateText
class by preceeding what you want to change with gui
. For example, say you wanted to change the text of your textarea. The code would be the following:
gui.textArea.setText("Works!");
祝您编程愉快!:)
这篇关于不能在另一个类的秋千组件中设置值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!