我正在尝试执行以下布局,其中所有 JPanel 在程序启动时都可见,但 panel2 除外。当用户单击 btn1 时,JCalendar 和 panel3 设置为不可见,而 panel2 变为可见。我遇到的问题是 panel2 没有显示 btn1 被点击。但是,如果我将 panel2 的边框布局更改为未使用的边框布局(在本例中为 WEST),它将在单击按钮时显示,但它在左侧对齐,我希望它在表单中居中。
代码:
public class GUI extends JFrame implements ActionListener, PropertyChangeListener
{
private JPanel panel1, panel2, panel3;
private com.toedter.calendar.JCalendar calendar;
private Button btn1, btn2;
private JLabel label1, label2;
public GUI()
{
init();
}
private void init()
{
//panel1 components
panel1 = new JPanel();
btn1 = new JButton("Click me");
panel1.add(btn1);
//panel2 components
panel2 = new JPanel();
label1 = new JLabel("Time:");
label2 = new JLabel("Date:");
panel2.add(label1); panel2.add(label2);
//JCalendar
calendar = new com.toedter.calendar.JCalendar();
//panel3
panel3 = new JPanel();
//Add panels to JFrame
add(panel1, BorderLayout.NORTH);
add(calendar, BorderLayout.CENTER);
add(panel2, BorderLayout.CENTER); //if i set this to WEST it show!!
add(panel3, BorderLayout.EAST);
//event handling
btn1.addActionListener(this);
//hide panel2
panel2.setVisible(false);
pack();
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource().equals(btn1)
{
calendar.setVisible(false);
panel3.setVisible(false);
panel2.setVisible(true); //make panel2 visible
panel2.updateUI();
revalidate();
repaint();
}
}
public static void main(String args[])
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new GUI().setVisible(true);
}
});
}
当我单击 btn1 时,JCalendar 和 panel3 不可见,但 panel2 不显示