Learning GUIs - setContentPane() method

Viewed 23276

I'm learning GUI programming in java, and trying to modify an existing programme to add a vertical left-hand panel containing buttons to my main frame.

The main method is below. Currently, the MainPanel class extends JPanel and contains the main components of the programme (a basic game). I want to create a new panel to the right of the game.

public static void main(String[] args) {
        JFrame frame = new JFrame("Sokuban");
        MainPanel panel = new MainPanel();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new BorderLayout());
        frame.setContentPane(panel);
        frame.pack();
        frame.setVisible(true);

}

I understand (I think!) how to add the buttons - I'm not stuck there.

I've tried things like:

    frame.add(new MyPanel(), BorderLayout.NORTH);

(MyPanel() being a new class that extends JPanel)

        window.setContentPane(panel, BoxLayout.X_AXIS);

(wouldn't compile)

What I am stuck with is a) whether I should try to create two JPanels contained within my JFrame, and then position them side by side using BoxLayout (??). Or, b) whether I should create a second JPanel to sit within the MainPanel, and somehow rearrange it there?

Also, despite reading the literature, I don't understand what the setContentPane() method is doing. Any pointers would be very much appreciated.

2 Answers
Related