1

Basically all I want to do is draw two rows of buttons for a lights out game (homework), but I don't know how to make both panels show up. I've pretty much almost no graphics before, and I don't really understand anything I'm doing. The panels them selves work, but it just shows whichever I add second (I assume it's overwriting the previous panel)

public static void main(String[] args) {
    String nButtonsString = JOptionPane.showInputDialog("How many buttons would you like?");
    int nButtons = Integer.parseInt(nButtonsString);
    JFrame myFrame = new JFrame();

    myFrame.setTitle("Linear Lights Out Game.");
    myFrame.setSize(FRAME_SIZE);    


    JPanel control_buttons = new Linear_Controls();
    myFrame.add(control_buttons);

    JPanel lights = new LinearLightsPanel(nButtons);
    myFrame.add(lights);

    myFrame.pack();
    myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    myFrame.setVisible(true);
icaughtfireonce
  • 171
  • 1
  • 10
  • Possible duplicate? http://stackoverflow.com/questions/4186835/how-to-add-multiple-components-to-a-jframe – Ordous Apr 11 '14 at 15:24
  • you can find code related to your request from here :http://www.java2s.com/Code/Java/Swing-Components/TabColorExample.htm – Raju Sharma Apr 11 '14 at 15:27

2 Answers2

2
myFrame.add(control_buttons);
myFrame.add(lights);

By default a JFrame uses a BorderLayout. Also, by default components get added to the CENTER of the BorderLayout. However the CENTER can only contain a single component so only the last component added is displayed. Try:

myFrame.add(control_buttons, BorderLayout.NORTH);

Now the two components should show up.

Read the section from the Swing tutorial on Using Layout Managers for more information and examples. Also take a look at the Trail/Table of Contents link to see other useful topics for basic Swing usage.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • How do I implement BoarderLayout in a custom class? DoI just store the Layout object I give it in a field and let java do the rest? – icaughtfireonce Apr 11 '14 at 15:31
  • @icaughtfireonce, I have no idea what you are asking. Read the tutorial for working examples and more detail explanations. – camickr Apr 11 '14 at 15:33
  • Never mind, I played with it and I guess I don't have to include the boarder layout in my constructor. This works, thanks. – icaughtfireonce Apr 11 '14 at 15:36
0

You have to create the 2 panels A and B and add them to another panel C. Then you add C to your frame.

A bit better explained: This is what you have now:

JPanel lights = new LinearLightsPanel(nButtons);
myFrame.add(lights);

But you would like something like:

JPanel lightsA = new LinearLightsPanel(nButtonsA);
JPanel lightsB = new LinearLightsPanel(nButtonsB);

JPanel lightsC = new JPanel();
lightsC.add(lightsA);
lightsC.add(lightsB);

myFrame.add(lightsC);
Daniel
  • 21,933
  • 14
  • 72
  • 101