Reputation: 323
I have created a jbutton
in the correct way (I'm assuming), and have added it to the jFrame
, is there any reason why I am unable to see my button when I run it?
import javax.swing.*;
import java.awt.*;
public class MainMenu{
public JFrame mainframe;
public JButton newGameBTN;
public JLabel title;
public MainMenu(){
mainframe = new JFrame("Java Assignment");
mainframe.setSize(220 ,480);
mainframe.setLocationRelativeTo(null);
mainframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
newGameBTN = new JButton("New Game");
title = new JLabel ( "Java Assignment",SwingConstants.CENTER);
mainframe.getContentPane().add(newGameBTN);
mainframe.getContentPane().add(title);
mainframe.setVisible(true);
}
}
Upvotes: 1
Views: 732
Reputation: 324157
mainframe.getContentPane().add(newGameBTN);
mainframe.getContentPane().add(title);
The default layout for the content pane of a JFrame is a BorderLayout. When you don't specify a constraint the component is added to the "CENTER". But you can only have a single component in the center so the second component added replaces the first component. Try:
mainframe.getContentPane().add(newGameBTN, BorderLayout.NORTH);
Upvotes: 3