MayNotBe
MayNotBe

Reputation: 2140

Java JPanels not visible in Frame

Can someone please explain why my frame only shows p2 and not p1?

This happens to me often and I know I'm missing something.

public class Exercise_16_4 extends JFrame {

private static final long serialVersionUID = 1L;

    JLabel[] labels = new JLabel[3];
    JTextField[] textFields = new JTextField[3];
    JButton[] buttons = new JButton[4];
    String[] buttonText = {"Add", "Subtract", "Multiply", "Divide"};
    String[] labelText = {"Number 1", "Number 2", "Result"};
    JPanel p1 = new JPanel();
    JPanel p2 = new JPanel();

    public Exercise_16_4() {
        for (int i = 0; i < labels.length; i++) {
            labels[i] = new JLabel(labelText[i]);
            textFields[i] = new JTextField();
            p1.add(labels[i]);
            p1.add(textFields[i]);
        }

        for (int i = 0; i < buttons.length; i++) {
            buttons[i] = new JButton(buttonText[i]);
            p2.add(buttons[i]);
        }

        add(p1);
        add(p2);
    }

    public static void main(String[] args) {
        Exercise_16_4 frame = new Exercise_16_4();
        frame.setTitle("Exercise 16.4");
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
}//main
}//class

Upvotes: 0

Views: 144

Answers (1)

camickr
camickr

Reputation: 324108

The default layout manager for the content pane of a JFrame is a BorderLayout.

By default when you add a component to the frame is will be added to the CENTER of the BorderLayout. The problem is only one component can be added so only the last one added is displayed.

You can try something like:

add(p1, BorderLayout.NORTH);

Or you can create a JPanel add the p1, p2 components to the panel and then add the panel to the frame.

Read the section from the Swing tutorial on Layout Managers for more information and examples of using layout managers as well as examples that show you how to create the GUI on the Event Dispatch Thread.

Upvotes: 5

Related Questions