如何将JButton彼此垂直放置? [英] How do I position JButtons vertically one after another?

查看:272
本文介绍了如何将JButton彼此垂直放置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I used a CardLayout to create 2 panels. The one on the left hosts JButtons, which when clicked, opens the corresponding website in the right panel. The problem is that I'm unable to place the buttons one on top of the other.

请查看以下屏幕截图:-

Please observe the screenshot below :-

推荐答案

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

您可以使用 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);  
}

运行此示例以查看

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

如果我想在按钮之间留些间隙怎么办?"

要在两次使用之间添加空格int,请使用

To add space int between use createVerticleStrut() in between the components

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

这篇关于如何将JButton彼此垂直放置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆