【发布时间】:2013-05-08 14:56:22
【问题描述】:
这是我第一次涉足 GridBagLayout,已经在线查看了 Java 文档(以及许多 SO Q&A),并且我创建了一个面板,我希望这样显示:
+--------------------------+
| choose a timer |
+--------+--------+--------+
| 5min | 25min | 30min |
+--------+--------+--------+
| 00:00:00 |
+--------+--------+--------+
| Start | Pause | Quit |
+--------+--------+--------+
这是我正在使用的 GridBagLayout。
public class ButtonSel extends JFrame implements ActionListener {
JLabel buttonSelLabel = new JLabel("Choose Which Timer To Run");
JButton pomoButton = new JButton("00:25:00");
JButton shrtButton = new JButton("00:05:00");
JButton longButton = new JButton("00:30:00");
JButton startButton = new JButton("Go");
JButton pauseButton = new JButton("Pause");
JButton quitButton = new JButton("Quit");
JLabel textDisplay = new JLabel("00:00:00");
//
JPanel timerPanel = new JPanel();
//
public ButtonSel() {
super("ButtonTest");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
add(buttonSelLabel, c); // line 1
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
c.gridy = 1;
c.gridwidth = 3;
add(pomoButton, c); // line 2
c.gridx = 1;
c.gridy = 2;
c.gridwidth = 1;
add(shrtButton, c);
c.gridx = 2;
c.gridy = 2;
c.gridwidth = 1;
add(longButton, c);
c.gridx = 3;
c.gridy = 2;
c.gridwidth = 1;
add(textDisplay, c); // line 3
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx=1;
c.gridy=3;
c.gridwidth=3;
add(startButton, c); // line 4
c.gridx = 1;
c.gridy = 4;
c.gridwidth = 1;
add(pauseButton, c);
c.gridx = 2;
c.gridy = 4;
c.gridwidth = 1;
add(quitButton, c);
c.gridx = 2;
c.gridy = 4;
c.gridwidth = 1;
pomoButton.addActionListener(this);
shrtButton.addActionListener(this);
longButton.addActionListener(this);
startButton.addActionListener(this);
pauseButton.addActionListener(this);
quitButton.addActionListener(this);
}
public void actionPerformed(ActionEvent radioSelect) {
Object source = radioSelect.getSource();
if (source == pomoButton)
textDisplay.setText("00:25:00");
else
if (source == shrtButton)
textDisplay.setText("00:05:00");
else
if (source == longButton)
textDisplay.setText("00:30:00");
else
if (source == startButton)
textDisplay.setText("Started");
else
if (source == pauseButton)
textDisplay.setText("Paused");
else
if (source == quitButton)
textDisplay.setText("Quit");
else
textDisplay.setText("00:00:00");
}
}
我得到了这个输出,
并从this question 中获取有关水平对齐的提示,我将HORIZONTAL 约束添加到字段中。现在我得到了:
我使用(0,0) 和(1,1) 作为我的起始(x,y) 坐标,有趣的是,结果相同。
谁能看到我遗漏的东西?
【问题讨论】:
-
您的代码不可运行,因此我无法对此进行测试,但您对所有组件都使用了相同的 GridBagConstraints 实例。我看到您为您的第一个组件设置 c.fill = GridBagConstraints.HORIZONTAL。这就是您想要的所有组件吗?在将 GridBagConstraints 添加到组件后,您还需要设置它们。在添加之前设置它们。
-
啊哈……做到了。我以为你在添加组件参数之前添加组件,但它应该是相反的:定义参数,然后添加组件。还;代码已更新,因此可以运行。
-
在这一点上,是的,我想要
HORIZONAL用于我的所有组件。一旦我让它工作并看到它的外观,我将决定是否保留它......
标签: java swing layout gridbaglayout