且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

通过循环添加JPanels

更新时间:2023-12-05 22:02:22

JPanel默认布局为FlowLayout,默认情况下将每个组件添加到右侧,以适合您的问题.

您可能还对 swingx 感兴趣,他们拥有HorizontalLayout.

示例:

//in some place
 JPanel myBigPanel = new JPanel();
 myBigPanel.setLayout(new HorizontalLayout()); // swingx api

List<MultitipleChoicePanel> panelList = new ArrayList<>();
// panelList.add(new MultipleChoicePanel()).. .n times

for(MultipleChoicePanel mp : panelList){
 myBigPanel.add(mp);
}

myBigPanel.revalidate(); // revalidate should call repaint but who knows
myBigPanel.repaint();

如何使用各种布局管理器

Made it work! Thank you guys!
The code follows. I used BoxLayout since I thought it'd be ideal for stacking questions one on top of the other, but now I got issues with the layout... When I stack several questions the question panels start overlapping. Any thoughts?

            panels1 = new MultipleChoice[5];
    setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
    for(int i=0; i<4; i++){
        panels1[i]= new MultipleChoice();
        panels1[i].setAlignmentX(CENTER_ALIGNMENT);
        add(panels1[i]);


    }
    setVisible(true);


I'm working on designing an Online Test applet.
A test has multiple choice and true/false questions. To set up a test I created two JPanel classes, one for the multiple choice question and one for the true/false questions. So when a test is created I'll just dynamically add these panels to a JPanel container according to the non-fixed number of questions.

First, how can I dynamically add new panels to a panel? I thought about declaring an array of the JPanel type. I created and then add objects of this panel class using a for loop:

MultitipleChoicePanel[] PanelArray;

for (...){
   PanelArray[i] =  new MultipleChoicePanel();
   containerpanel.add(PanelArray[i]);
   }

I don't know if this is technically possible.
This is my first time using Swing, and I tried doing this but obviously it didn't work.
Does anyone have an idea how correctly dynamically add these panels?

Second, which of the layout managers is best suited for the container panel in order to fit every new panel added right under the previous one?
I thought about dynamically setting up a GridLayout of one column and add rows as I add panels. But I've been really struggling modifying swings dynamically.
Any suggestions?

Thank you so much for your help!

JPanel default layout is FlowLayout and add each component by default to the right so it would fit your problem.

You also may interested in swingx they have HorizontalLayout.

Example:

//in some place
 JPanel myBigPanel = new JPanel();
 myBigPanel.setLayout(new HorizontalLayout()); // swingx api

List<MultitipleChoicePanel> panelList = new ArrayList<>();
// panelList.add(new MultipleChoicePanel()).. .n times

for(MultipleChoicePanel mp : panelList){
 myBigPanel.add(mp);
}

myBigPanel.revalidate(); // revalidate should call repaint but who knows
myBigPanel.repaint();

How to use various Layout Managers