我写了一种创建表单的方法,然后在main中写了一些其他命令。(java)

package pak2;
import javax.swing.*;

public class form6 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

          JFrame jframe = new JFrame();

          JButton jButton = new JButton("JButton");

          jframe.getContentPane().add(jButton);

          jframe.pack();
          jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          jframe.setVisible(true);

            System.out.println("test***ok");//testtttttttttttttt


    }
}


我想执行“ System.out.println(“ test *** ok”);“之后,表格被关闭。
 但是当我运行程序时,在以表格形式输入信息之前,将执行其他命令!
表单运行时,将执行其他命令!我该如何设置。

最佳答案

您在这方面走错了路。

这是一个带有注释的示例:

public class Form2  {

    public static void main(String[] args) {

        final JFrame jframe = new JFrame();

        final JButton jButton = new JButton("JButton");

        /**
         * Once you create a JFrame, the frame will "listen" for events.
         * If you want to do something when the user clicks a button for example
         * you need to add an action listener (an object that implements ActionListener)
         *
         * One way of doing this is by using an anonymous inner class:
         */
        jButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if (e.getSource().equals(jButton)){
                    jframe.dispose();
                    System.out.println("Button clicked!");
                }

            }
        });

        jframe.getContentPane().add(jButton);
        jframe.pack();
        jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // displaying the form will NOT block execution
        jframe.setVisible(true);
        System.out.println("test***ok");// testtttttttttttttt
    }
}

10-08 13:17