James Lee
James Lee

Reputation: 13

How to for loop jPanel in jFrame?

May I know why my jPanel does not appear in the jFrame? I want to make 5 blue jPanel appear in the jFrame but why only 1 blue jPanel appear in my jFrame? Thanks for helping!

public class NewJFrame2 extends javax.swing.JFrame {

    JFrame frame = new JFrame();
    JPanel panel = new JPanel();
/**
 * Creates new form NewJFrame2
 */
public NewJFrame2() {
    initComponents();
    JPanel[] panelArray = new JPanel[5];
    JButton btnArray[] = new JButton[5];
    for(int i = 0; i<5;i++)
    {
        panelArray[i] = new JPanel();
        //panelArray[i].setVisible(true);
        System.out.println(panelArray[i]);
        javax.swing.border.Border border = BorderFactory.createLineBorder(Color.BLUE, 5);
        panelArray[i].setBackground(Color.YELLOW);
        panelArray[i].setBorder(border);
        frame.getContentPane().add(panelArray[i]);

    }

    frame.setSize(new Dimension(500, 400));

    frame.setLocationRelativeTo(null);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.setTitle("A Simple JFrame");

    frame.setVisible(true);
}

Upvotes: 0

Views: 789

Answers (2)

nullPointer
nullPointer

Reputation: 4574

Using a container JPanel with a BoxLayout -- see comments below for further info :

    initComponents();
    JPanel[] panelArray = new JPanel[5];
    JButton btnArray[] = new JButton[5];
    JPanel container = new JPanel(); // Container JPanel   
    container.setLayout(new BoxLayout(container, BoxLayout.X_AXIS)); // With a BoxLayout
    for (int i = 0; i < 5; i++) {
        panelArray[i] = new JPanel();
        //panelArray[i].setVisible(true);
        System.out.println(panelArray[i]);
        javax.swing.border.Border border = BorderFactory.createLineBorder(Color.BLUE, 5);
        panelArray[i].setBackground(Color.YELLOW);
        panelArray[i].setBorder(border);
        container.add(panelArray[i]);   // Adding 5 JPanels to container JPanel
    }
    frame.getContentPane().add(container); // Adding container JPanel to JFrame
    frame.setSize(new Dimension(500, 400));
    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setTitle("A Simple JFrame");
    frame.setVisible(true);

Upvotes: 0

M. Goodman
M. Goodman

Reputation: 151

As mentioned in the comments you want a LayoutManager.

The current issue is that you are adding all five panels to the exact same space on your frame. To solve this issue you need to provide a structure for the frame to associate different coordinates with different areas.

This answer contains a good jumping off point for you to start to play with layouts in Java.

Upvotes: 1

Related Questions