Java Swing - 新行上的JButtons

时间:2011-11-17 02:40:33

标签: java swing

我正在尝试使用新行上的每个按钮打印出动态生成的按钮列表。

public void addComponentToPane(Container pane) {
    JTabbedPane tabbedPane = new JTabbedPane();

    //Create the "cards".
    JPanel card1 = new JPanel() {

 JPanel card1 = new JPanel()     
 ... 

int n = 10;
JButton[] jButtons = new JButton[10];
for(int i=0; i<n; i++){
   jButtons[i] = new JButton("test" + i);
   card1.add(jButtons[i]);
   //card1.add("<br>");//<--this is wrong; but hopefully you get my point.
   jButtons[i].addActionListener(this);
}

4 个答案:

答案 0 :(得分:4)

将它们放入一个盒子中:

Box card1 = Box.createVerticalBox();

或者,如果您希望所有按钮具有相同的大小,请使用GridLayout和一列:

JPanel card1 = new JPanel(new GridLayout(n, 1))

答案 1 :(得分:4)

以下是使用约束GridLayoutBoxLayout

的两种解决方案

Dynamic Buttons

我更喜欢GridLayout(左侧),因为它标准化了按钮的宽度,并且可以轻松地在它们之间添加一个小空间。

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class DynamicButtons {

    public static void main(String[] args) {
        final JPanel gui = new JPanel(new BorderLayout());

        final JPanel gridButton = new JPanel(new GridLayout(0,1,2,2));
        gridButton.add(new JButton("Button 1"));
        JPanel gridConstrain = new JPanel(new BorderLayout());
        gridConstrain.add(gridButton, BorderLayout.NORTH);

        final Box boxButton = Box.createVerticalBox();
        boxButton.add(new JButton("Button 1"));

        JButton b = new JButton("Add Button");
        b.addActionListener( new ActionListener() {
            int count = 2;
            public void actionPerformed(ActionEvent ae) {
                gridButton.add(new JButton("Button " + count));

                boxButton.add(new JButton("Button " + count));

                count++;
                gui.revalidate();
            }
        });

        gui.add(b, BorderLayout.NORTH);
        JSplitPane sp = new JSplitPane(
            JSplitPane.HORIZONTAL_SPLIT,
            new JScrollPane(gridConstrain),
            new JScrollPane(boxButton));
        gui.add(sp, BorderLayout.CENTER);

        gui.setPreferredSize(new Dimension(250,150));

        JOptionPane.showMessageDialog(null, gui);
    }
}

答案 2 :(得分:3)

使用GridBagLayout并设置GridBagConstaints.gridy字段。

答案 3 :(得分:3)

我想你需要这样的东西:

enter image description here

为此,您需要Box Layout,有关详细信息,请参阅此处:How to Use BoxLayout

如果需要,还有一个演示:Java Tutorials Code Sample – BoxLayoutDemo.java