我试图访问 main() 内的 jTextArea,但收到错误消息,“无法在静态上下文中访问非静态成员”
。因此我通过以下方式访问:(使用netbeans)
public static void main(String args[]) throws Exception {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new UserInterface().setVisible(true);
}
});
sample ss=new sample();
System.out.println("Inside Main()");
ss.display("Happy");
}
class sample
{
void display(String message)
{
UserInterface ui=new UserInterface();
System.out.println("inside sample:"+message);
ui.jTextArea2.append(message);
String aa=ui.jTextArea2.getText();
System.out.println("Content of JTextArea2:"+aa);
}
}
我已将变量声明为:public javax.swing.JTextArea jTextArea2;
我得到以下输出:
Main() 内部
内部示例:快乐
JTextArea2的内容:快乐
但问题是:GUI 中的 jTextArea2 中没有显示该消息。
最佳答案
您已经创建了两个不同的对 UserInterface
的引用...
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
// Here's one...
new UserInterface().setVisible(true);
}
});
//...
void display(String message)
{
// And here's another
UserInterface ui=new UserInterface();
现在这两个引用彼此无关,对其中一个引用的任何修改都不会影响另一个引用。
如果你没有这样做:
public static void main(String args[]) throws Exception {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
UserInterface ui = new UserInterface();
ui.jTextArea2.append(message);
ui.setVisible(true)
}
});
}
您应该发现它有效。
更新
从public static void main(String[] agrs)
加载类一直在完成,否则有点难以完成任何事情;)
public class UserInterface extends javax.swing.JFrame {
public static void main(String args[]) throws Exception {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
UserInterface ui = new UserInterface();
// Happy interactions :D
}
});
}
}
关于java - 在 main() 中访问 jTextArea,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12667611/