gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 18:36:46 27 4
gpt4 key购买 nike

我使用 CardLayout 创建了 2 个面板。左侧的托管 JButtons,单击它会在右侧面板中打开相应的网站。问题是我无法将按钮一个放在另一个之上。

请观察下面的截图:-

Screen Shot

最佳答案

"The problem is that I'm unable to place the buttons one after the other."

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

enter image description here

编辑:

"How about if I want to leave gaps between the buttons ?"

在使用 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));

enter image description here

关于java - 如何一个接一个地垂直放置 JButton?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20737064/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com