[英]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: 或者,如果您希望所有按钮的大小都相同,请使用GridLayout和一列:
JPanel card1 = new JPanel(new GridLayout(n, 1))
Here are two solutions using a constrained GridLayout
and a BoxLayout
这是使用受约束的
GridLayout
和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. 我更喜欢
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);
}
}
使用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 为此,您需要Box Layout ,有关更多详细信息,请参见: 如何使用BoxLayout
and if needed here is a demo : Java Tutorials Code Sample – BoxLayoutDemo.java 如果需要,这里是一个演示: Java教程代码示例– BoxLayoutDemo.java
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.