1

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);  
    }
}
ThomasMcDonald
  • 293
  • 3
  • 7
  • 18

1 Answers1

3
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);
camickr
  • 321,443
  • 19
  • 166
  • 288
  • new problem, the newGameBTN jButton is the same size as the jFrame, even though it has its parameters set using .setSize(); . – ThomasMcDonald Oct 29 '14 at 00:21
  • 1
    @ThomasMcDonald, read the tutorial on [Layout Manager](http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html). Start by reading how the BorderLayout works so you understand better. Then read up on the other layout managers and use the one (or combination of) layout managers that does what you want. Never use setSize() when using a layout manager. – camickr Oct 29 '14 at 03:01