【发布时间】:2017-12-17 07:16:40
【问题描述】:
我有一个JPanel,其中包含两个JToggleButtons。该面板有一个GridBagLayout,并且有 1 行和 2 列。按钮位于同一行,但不同的列。
class UserInterfacePanel extends JPanel {
private JToggleButton startButton;
private JToggleButton stopButton;
public UserInterfacePanel() {
setup();
}
private void setup() {
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
setupButtons();
//setupButtonsActions();
c.insets=new Insets(3,3,3,3);
c.weightx=0.5; //c.weightx=0.0;
c.weighty=0.5; //c.weighty=0.5;
c.gridx=0;
c.gridy=0;
add(startButton, c);
c.gridx=1;
c.gridy=0;
add(stopButton, c);
}
private void setupButtons() {
startButton=new JToggleButton(iconStartButton);
stopButton=new JToggleButton(iconStopButton);
}
public class UserInterface extends JFrame {
public static void main(String[] args) {
run();
}
public UserInterface() {
setup();
}
private void setup() {
width=800;
height=600;
panel=new UserInterfacePanel();
getContentPane().add(panel);
setSize(width, height);
}
public static void run() {
UserInterface gui=new UserInterface();
gui.setVisible(true);
}
}
我希望能够控制按钮之间的间距,但更改 c.gridwidth 或 c.weightx 并没有给我结果。将c.wightx 设置为 0.0 会导致按钮彼此太近,而除零以外的任何值都会导致它们太远,c.widthx=0.9 和 c.widthx=0.1 之间的距离没有差异。我做错了什么?
【问题讨论】:
-
1) 需要设置的可能是
GridBagConstraints.insets、ipadx或ipady。 2) 为了尽快获得更好的帮助,请发布minimal reproducible example 或Short, Self Contained, Correct Example。 3) 以最小尺寸提供 ASCII 艺术或 GUI 的预期布局的简单绘图,如果可调整大小,则具有更大的宽度和高度。 -
@Andrew Thompson,我编辑了帖子,现在应该可以运行了。
标签: java swing layout-manager gridbaglayout