Isuru
Isuru

Reputation: 3958

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?

Upvotes: 2

Views: 122

Answers (4)

Daan
Daan

Reputation: 1546

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

Upvotes: 2

MAK
MAK

Reputation: 26586

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.

Upvotes: 1

Starkey
Starkey

Reputation: 9781

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

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1500525

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.

Upvotes: 3

Related Questions