简体   繁体   中英

Java Swing - JButtons on New Line

I am trying to print out a dynamically generated list of buttons with each button on a new line.

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);
}

Put them into a box:

Box card1 = Box.createVerticalBox();

or, if you want all the buttons to have the same size, use GridLayout with one column:

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

Here are two solutions using a constrained GridLayout and a BoxLayout

动态按钮

I prefer the GridLayout (on the left) since it normalizes the width of the buttons and makes it easy to add a small space between them.

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);
    }
}

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

I suppose you need something like this :

在此处输入图片说明

For this you require a Box Layout , see this for more details : How to Use BoxLayout

and if needed here is a demo : Java Tutorials Code Sample – BoxLayoutDemo.java

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM