我正在尝试从其他类更新GUI。每次我尝试在不同的类上调用该方法都行不通,但是如果我在GUI类中执行该方法就可以了。
GUI类:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Test7 extends JPanel implements ActionListener {
private JButton jcomp1;
private JButton jcomp2;
private JButton jcomp3;
private JTextField jcomp4;
public Test7() {
//construct components
jcomp1 = new JButton("Button 1");
jcomp2 = new JButton("Button 2");
jcomp3 = new JButton("Button 3");
jcomp4 = new JTextField(5);
jcomp1.addActionListener(this);
//adjust size and set layout
setPreferredSize(new Dimension(723, 455));
setLayout(null);
//add components
add(jcomp1);
add(jcomp2);
add(jcomp3);
add(jcomp4);
//set component bounds (only needed by Absolute Positioning)
jcomp1.setBounds(160, 320, 100, 20);
jcomp2.setBounds(340, 320, 100, 20);
jcomp3.setBounds(490, 315, 140, 20);
jcomp4.setBounds(180, 125, 365, 110);
}
public static void main(String[] args) {
JFrame frame = new JFrame("MyPanel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new Test7());
frame.pack();
frame.setVisible(true);
}
public void setTextArea(JTextField jcomp4) {
this.jcomp4 = jcomp4;
}
public JTextField getTextArea() {
return this.jcomp4;
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == jcomp1) {
Class class1 = new Class();
class1.start();
}
}
}
第二堂课
public class Class extends Test7{
public void start(){
Test7 form = new Test7();
form.getTextArea().setText("nesto");
}
}
我还尝试将代码放在同一线程上,但这似乎也不起作用。
答案 0 :(得分:2)
Test7
是JPanel。它是在您的main方法中添加到JFrame的。呼叫Class.start()
时,您将创建新的Test7
。这个新的JPanel与先前添加到JFrame的JPanel无关,因此甚至不可见。
您的Class
类不应扩展也不能创建新的Test7
实例。相反,可以将Test7
实例在构造函数中传递给Class
:
Class class1 = new Class(this);
class1.start();
您的Class
类:
public class Class {
private final Test7 test;
public Class(Test7 test) {
super();
this.test = test;
}
public void start() {
test.getTextArea().setText("nesto");
}
}
安德鲁(Andrew)的评论也值得考虑。