-2

I am new to programming and have just started learning GUI and was wondering why my GUI isn't showing my button, also i want it to exit the application as it is pressed. I'm unsure on what to do next, could someone help me pls :) I would be very greatful.

public class Main implements ActionListener {
    public static void GUI(){

        JFrame frame = new JFrame();
        JPanel panel = new JPanel();
        JButton exit = new JButton();
        panel.setBorder(BorderFactory.createEmptyBorder(1080, 720, 1080, 720));
        panel.setLayout(new GridLayout(0, 1));
        exit.setSize(10, 20);
        exit.setBounds(100, 400, 100, 600);
        frame.add(exit);
        frame.add(panel, BorderLayout.CENTER);
        //exit.add(exit);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 400);
        frame.setLocationRelativeTo(null);
        frame.setTitle("Gabe's GUI app");
        frame.pack();
        frame.setContentPane(panel);
        frame.setVisible(true);
        exit.setVisible(true);
    }
    public static void main (String[] args) {
        GUI();
    }

    @Override
    public void actionPerformed(ActionEvent e) {


    }
}
camickr
  • 321,443
  • 19
  • 166
  • 288
  • 2
    Welcome to SO. What have you tried/searched so far? Is [this](https://stackoverflow.com/questions/25026807/how-to-display-a-jbutton-and-give-it-functionality) helpful? – fjsv Jun 13 '20 at 17:08

2 Answers2

2

The default layout manager of the content pane of a JFrame is the BorderLayout. You can only add a single component to each area of the BorderLayout.

frame.add(exit);
frame.add(panel, BorderLayout.CENTER);

If you don't specify a constraint when adding the component, then BorderLayout.CENTER is used.

So in your above code "panel" replaces "exit" in the CENTER.

Try:

frame.add(exit, BorderLayout.PAGE_END);
frame.add(panel, BorderLayout.CENTER);

I am new to programming

Start by reading the Swing tutorial for Swing basics. There are many examples you can download and test.

Start with the examples in How to Use BorderLayout. The example will also show you how to better structure your code so the GUI is created on the Event Dispatch Thread (EDT). All components should be created on the EDT.

camickr
  • 321,443
  • 19
  • 166
  • 288
0

To close the JFrame on click on exit, write exit.addActionListener(this); and in actionPreformed method write frame.dispose();.

Programmer
  • 803
  • 1
  • 6
  • 13