user3773076
user3773076

Reputation:

Java GUI is launching but nothing appears, no errors in stack trace

I'm trying to play around with ActionListeners and inner classes through a simple GUI where a user will press a button which will cause a message to be displayed.

My code compiles - however, upon launch, the icon will appear in my tray (OSX), but then immediate terminate. No errors appear in my console.

Here is my code:

import javax.swing.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;

public class GUI {

    private JFrame myFrame;
    private JPanel messagePanel;
    private JPanel buttonPanel;

    private JLabel myMessage;

    public GUI() {

        myFrame = new JFrame("My GUI");
        messagePanel = new JPanel();
        buttonPanel = new JPanel();
        myMessage = new JLabel();

        myFrame.setLayout(new BorderLayout());
        myFrame.setSize(500, 500);
        myFrame.add(messagePanel, BorderLayout.SOUTH);
        myFrame.add(buttonPanel, BorderLayout.CENTER);

        messagePanel.add(myMessage);

        addButtons();
    }

    public void addButtons() {

        JButton button1 = new JButton(new ImageIcon("circle.png"));
        buttonPanel.add(button1);

        button1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                myMessage.setText("Button pressed!");
            }
        });

    }

    public static void main(String[] args) {
        GUI myGUI = new GUI();
    }


}

What's going on here?

Upvotes: 0

Views: 90

Answers (2)

David Yee
David Yee

Reputation: 3646

You need to make the JFrame, myFrame, visible via myFrame.setVisible(true);

Also, you should not run any Swing GUI related code outside the Event Dispatch Thread (EDT). The correct way to start your program would be:

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                GUI myGUI = new GUI();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

Upvotes: 4

Amir Afghani
Amir Afghani

Reputation: 38531

After addButtons() in your constructor, add the following statement:

    myFrame.setVisible(true);

Upvotes: 1

Related Questions