这是我第一次涉足 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");
}
}
我得到这个输出,
并从这个问题中得到关于水平对齐的提示,我将HORIZONTAL
约束添加到字段中。现在我得到:
有趣的是,我使用(0,0)
和(1,1)
作为我的起始坐标,结果相同。(x,y)
谁能看到我缺少的东西?