mickzer
mickzer

Reputation: 6338

Adding JPanels to JFrame with a for loop

I have a JPanel, window and an array of JPanels and JLabels. I want to add 5 JPanels to the JFrame and a JLabel to each JPanel. Each JPanel will be used to represent data about a Dice.

However when I run the code, Only the last JPanel appears on the JFrame with text "Dice 4". I don't understand why.

The code:

public static void main(String args[]) {

    JFrame window = new JFrame("DICE Frame");
    window.setVisible(true);
    window.setTitle("DIE");
    window.setSize(400, 200);
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel[] diceView=new JPanel[5];
    JLabel[] labels=new JLabel[5];
    for(int i=0; i<diceView.length; i++) {

        diceView[i]=new JPanel();

        window.add(diceView[i]);

        labels[i]=new JLabel();
        labels[i].setText("Dice "+i);
        diceView[i].add(labels[i]);

    }
}

Upvotes: 1

Views: 2132

Answers (3)

Farmer Joe
Farmer Joe

Reputation: 6070

Your JFrame has the default BorderLayout specified. Try using a different Layout, something like this:

window.setLayout(new FlowLayout());

You will see your other JPanels. Check this out for more detailed info

Upvotes: 2

yilmazburk
yilmazburk

Reputation: 917

Because your JPanels added over and over and Dice 0, Dice 1, Dice 2, Dice 3 stay under Dice 4 therefore you can see only Dice 4. If you want to see other Dices then you should use layouts like flowlayout, boxlayout...

Upvotes: 2

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

A JFrame's contentPane (what you add things to when you call JFrame#add(...)) uses BorderLayout by default, and whenever you add a component to it in a default way, the component gets added BorderLayout.CENTER.

The solution is to add your other JPanels to a JPanel that uses whatever layout you feel necessary (or nested JPanels that use layouts), and then add this container JPanel to your JFrame, BorderLayout.CENTER.

Please have a look at the Layout Manager Tutorial for more on this. A key concept to understand is that you can nest JPanels, each using its own simple layout manager and thereby achieve a complex layout using only simple easy to use layout managers.

Upvotes: 3

Related Questions