如何一个接一个地垂直放置JButton?

Raj*_*ora 2 java swing jbutton layout-manager

我用a CardLayout来创建2个面板.左侧主机上的JButtons那个,单击时,会在右侧面板中打开相应的网站.问题是我无法将按钮放在另一个上面.

请注意以下截图: -

屏幕截图

Pau*_*tha 9

"问题在于我无法一个接一个地放置按钮."

你可以Box垂直使用一组

JButton jbt1 = new JButton("Button1");
JButton jbt2 = new JButton("Button2");
JButton jbt3 = new JButton("Button3");
JButton jbt4 = new JButton("Button4");

public BoxTest(){
    Box box = Box.createVerticalBox();    // vertical box
    box.add(jbt1);
    box.add(jbt2);
    box.add(jbt3);
    box.add(jbt4);

    add(box);  
}
Run Code Online (Sandbox Code Playgroud)

运行此示例以查看

import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class BoxTest extends JPanel{

    JButton jbt1 = new JButton("Button1");
    JButton jbt2 = new JButton("Button2");
    JButton jbt3 = new JButton("Button3");
    JButton jbt4 = new JButton("Button4");

    public BoxTest(){
        Box box = Box.createVerticalBox();
        box.add(jbt1);
        box.add(jbt2);
        box.add(jbt3);
        box.add(jbt4);

        add(box);  
    }

    public static void createAndShowGui(){
        JFrame frame = new JFrame();
        frame.add(new BoxTest());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationByPlatform(true);
        frame.pack();
        frame.setVisible(true);

    }
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable(){
            public void run(){
                createAndShowGui();
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

编辑:

"如果我想在按钮之间留下空隙怎么样?"

createVerticleStrut()在组件之间使用之间添加空间int

    Box box = Box.createVerticalBox();
    box.add(jbt1);
    box.add(Box.createVerticalStrut(10));  <-- 10 being the space
    box.add(jbt2);
    box.add(Box.createVerticalStrut(10));
    box.add(jbt3);
    box.add(Box.createVerticalStrut(10));
    box.add(jbt4);
    box.add(Box.createVerticalStrut(10));
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述