我正在努力向按钮面板添加按钮,以更熟悉 java.swing类。有没有一种方法可以将JButton的大小设置为按钮标签的长度和宽度?
类似于将xml文件中的高度和宽度视图设置为 wrap_content 或 match_parent 。根据其内容或父级的尺寸而不是尺寸来设置视图或布局的尺寸明确指定尺寸。
android:layout_width="wrap_content"
android:layout_height="match_parent"
是否可以使用 button.setPreferredSize()将JButton的大小设置为按钮标签的长度和宽度,而无需明确指定尺寸?
button = new JButton[buttonName.length];
RadioButtonAction radioButtonEventO=new RadioButtonAction(); //O for operation
buttonPanelS=new JPanel();
buttonPanelS.setLayout(new GridLayout(4,1));
for(int i=0; i<buttonName.length;i++){
button[i]=new JButton(buttonName[i]);
button[i].setMargin(new Insets(0,0,0,0));
button[i].addActionListener(radioButtonEventO);
//button[i].setPreferredSize();
buttonPanelS.add(button[i]);
}
operationPanel.add(buttonPanelS);
答案 0 :(得分:2)
我不是100%理解的人,但是GridLayout
将通过设计来确定所有组件的大小,以均匀地占据容器的可用空间。
听起来更像是GridBagLayout
...
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
JButton[] button = new JButton[5];
JPanel buttonPanelS = new JPanel();
buttonPanelS.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
for (int i = 0; i < 5; i++) {
button[i] = new JButton(random());
button[i].setMargin(new Insets(0, 0, 0, 0));
buttonPanelS.add(button[i], gbc);
}
add(buttonPanelS);
}
private Random rnd = new Random();
public String random() {
int length = rnd.nextInt(20) + 1;
StringBuilder sb = new StringBuilder(length);
for (int index = 0; index < length; index++) {
sb.append(('a' + rnd.nextInt(52)));
}
return sb.toString();
}
}
}
如果这不是您想要的,那么请考虑提供一张图纸,以更好地说明您的问题