简体   繁体   中英

Java - What's wrong with this simple program?

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class Test extends JFrame{

    JLabel label = new JLabel("Leann will come again");
    JButton yesButton = new JButton("Yes");
    JButton noButton = new JButton("Yes");
    JPanel panel = new JPanel();

    public Test(){

        panel.add(label);
        panel.add(yesButton);
        panel.add(noButton);
        add(panel);
        //setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        addAction();

    }

    public void addAction(){
        yesButton.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent arg0) {
                JOptionPane.showMessageDialog(null, "Are you sure?");               
            }

        });

        noButton.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent arg0) {
                JOptionPane.showMessageDialog(null, "Too bad!");                
            }

        });
    }

    public static void main(String args[]){
        Test app = new Test();

    }

}

when I run this in my ubuntu computer with eclipse, it get's stop(terminate) without any errors. There is no errors in the console either. And no syntax errors.

What's wrong? Is it because I run openjdk?

You don't set your frame to visible setVisible(true)

You should check out this tutorial: http://download.oracle.com/javase/tutorial/uiswing/components/frame.html

You're creating an instance of Test, but that's all. You're never actually trying to show it.

If you call app.setVisible(true) it will display, and the call will block.

You need to call setVisible(true) on your Test instance. It's also best to run this code in another thread.

public static void main(String[] args) {
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            Test app = new Test();
            app.setVisible(true);
        }
    }
}

Add this line at the end of your constructor:

setVisible(true);

Otherwise the JFrame never gets shown and the program exits. You might want to uncomment the setDefaultCloseOperation bit as well - although that is unrelated to your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM