1

main() 内の jTextArea にアクセスしようとしていますが、"Non-static members cannot be accessed in static context". したがって、次の方法でアクセスしました:(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:Happy の内容

しかし問題は、メッセージが GUI の jTextArea2 に表示されないことです。

4

1 に答える 1

2

UserInterface...への 2 つの異なる参照を作成しました。

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();

現在、これら 2 つの参照は互いに関係がなく、一方を変更しても他方には影響しません。

次のようなことをしなかった場合:

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
            } 
        }); 
    }
}
于 2012-10-01T05:02:33.020 に答える