Question

I am trying to add to JPanels to JFrame but the second one just go on top of the first one and I can't seem to understand why or how to fix it.

Below is the UI that I try to add. Thanks a lot,

Rotem

private static void createAndShowGUI() {
    JFrame f = new JFrame("Maman 13 - Part 2");
    f.setLayout(new BorderLayout());
    //f.setResizable(false);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    FlowLayout alignLeftLayout = new FlowLayout(FlowLayout.LEFT, 5, 5);
    // first row
    Hashtable<Integer, JButton> hashTable = new Hashtable<Integer, JButton>();
    LinkedHashMap<String, Integer> buttons = new LinkedHashMap<String, Integer>();
    addFirstRow(buttons);
    JPanel firstRow = new KeyboardRow(hashTable, buttons);
    firstRow.setLayout(alignLeftLayout);
    f.add(firstRow);
    // second row
    buttons = new LinkedHashMap<String, Integer>();
    addSecondRow(buttons);
    JPanel secondRow = new KeyboardRow(hashTable, buttons);
    secondRow.setLayout(alignLeftLayout);
    f.add(secondRow);

    f.pack();
    f.setVisible(true);
}
Was it helpful?

Solution

Instead of

f.setLayout(new BorderLayout());

try

f.setLayout(new GridLayout());

OTHER TIPS

I think you need to do like

f.add(firstRow, BorderLayout.WEST)

and

f.add(secondRow, BorderLayout.EAST)

or something like that. You are not specifying how to use the BorderLayout scheme you added.

Try using the following to replace your f.add([something]); lines.

f.add(firstRow, BorderPanel.LINE_START);
f.add(secondRow, BorderPanel.LINE_END);

This should put the firstRow panel on the left, and the secondRow panel on the right.

This works because a BorderLayout is built to hold up to five panels, as explained here: http://docs.oracle.com/javase/7/docs/api/java/awt/BorderLayout.html

Your existing code just adds the new panels to f, without specifying where they should go.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top