0

I'm making a Game where I have to DrawingComponent painting everything related to the game. Now I want to add a "close" button over the DrawingComponent.

public class SimulationWindow extends JFrame 
{
private static final long serialVersionUID = 1L;

public SimulationWindow()
{
    super("Game");
    setUndecorated(true);
    setExtendedState(JFrame.MAXIMIZED_BOTH); 


    getContentPane().setBackground(Color.BLACK);
    setLocationRelativeTo(null);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JButton closeButton = new JButton();
    closeButton.addActionListener(new ActionListener()
    {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            Game.close = true;
        }
    });

    add(new DrawingComponent());
    add(closeButton);

    setVisible(true);
}

}

But it's just a grey area that pops up. The DrawingComponent which is essentially the game is not visible.

  • 1
    1) By default `JFrame` uses [`BorderLayout`](https://docs.oracle.com/javase/7/docs/api/java/awt/BorderLayout.html) which by default places the elements in the `CENTER` position. You need to add `closeButton` at the end like: `add(closeButton, BorderLayout.SOUTH);` or wherever you want to add it. 2) Don't extend `JFrame` instead [create an instance of it](https://stackoverflow.com/questions/22003802/extends-jframe-vs-creating-it-inside-the-program) – Frakcool Jun 22 '18 at 17:24

1 Answers1

0
add(new DrawingComponent());
add(closeButton);

You can only add a single component to the BorderLayout.CENTER, which is the default location when you don't specify a constraint.

If you want the button added to the drawing panel the basic code would be:

DrawingComponent draw = new DrawingComponent();
draw.setLayout(...); // set the appropriate layout manager
draw.add( closeButton );
add(draw, BorderLayout.CENTER); // explicitly see the location 
camickr
  • 321,443
  • 19
  • 166
  • 288