0

ユーザーから文字列を取得し、ユーザーが送信ボタンをクリックするJavaでGUIを作成する必要があります。送信ボタンをクリックすると、ユーザーは文字列に対して何らかの処理を行い、画面(GUI)に出力を提供します。

今まで次のコードを書いてきましたが、このコードを実行しても何も出力されません。

public class userinterface extends javax.swing.JFrame {
   
    public userinterface() {
        initComponents();
    }
                   
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration                   
    
    public void show() {
        String str = jTextField1.getText();
                        
        jButton1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                //Execute when button is pressed
                System.out.println("You clicked the button,str");
            }
        });
    }

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new userinterface().setVisible(true);
                userinterface obj = new userinterface();
                obj.show();
            }
        });
    }

}

どこが間違っているのか教えてください。出力をGUI画面に表示するにはどうすればよいですか?

ありがとう。

4

2 に答える 2

4

あなたの問題は、重要なメソッドshow()を気付かずにオーバーライドしたことであり、これにより JFrame が表示されなくなります。このメソッドの名前を別の名前に変更します。

public void myShow() {
  // String str = jTextField1.getText(); // not useful

  jButton1.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {
        // Execute when button is pressed
        System.out.println("You clicked the button,str");
     }
  });
}

public static void main(String args[]) {
  java.awt.EventQueue.invokeLater(new Runnable() {
     public void run() {
        // new userinterface().setVisible(true);
        userinterface obj = new userinterface();
        // obj.show();
        obj.myShow();
        obj.setVisible(true);
     }
  });
}

これは、どうしても必要な場合を除き、クラスを拡張しないように努めるべきもう 1 つの理由です。

コード全体にprintlnを配置し、明示的に呼び出されていない場合でもshow()が呼び出されていることを確認することで、これをデバッグできました。

于 2012-04-21T17:31:17.010 に答える