java - 在 main() 中访问 jTextArea

标签 java swing

我试图访问 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/

相关文章:

java - Thymeleaf:检测硬编码文本

java - 保持远程 EJB 和 Web 服务的状态

java - eclipse安装错误

java - GUI JPanel 和 jframe 布局

java - 如何在 Swing 中更新 Jlabel 文本

Java 图表编辑器

java - 与 ^.*(?=.*\\d)(?=.*[a-zA-Z])(?=.*[!@#$%^&]).*$ 匹配的单词

java - 在新值(value)出现之前先弄清楚科学按钮

Java - 我想使用计时器绘制多个 2D 椭圆,但它不起作用

java - 拥有内部 JPanel