java Swing GUI 入门-切换布局
觉得有用的话,欢迎一起讨论相互学习~
布局
- 大部分和上一节: https://xuzhiwei.blog.csdn.net/article/details/111498257 的内容一致,新加入的内容有
- 通过按钮切换Panel
- Panel的叠加
- 布局,并向底部的ParentPanel中添加三个同等大小的panel相互叠加在一起.并且具有不同的颜色.
添加事件
- 向Button1中添加按钮事件以只显示panel1
card1button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
parentPanel.removeAll();
parentPanel.add(card1Panel);
parentPanel.repaint();
parentPanel.revalidate();
}
});
}
- 向Button2中添加按钮事件以只显示panel2
- 向Button2中添加按钮事件以只显示panel3
card2Button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
parentPanel.removeAll();
parentPanel.add(card2Panel);
parentPanel.repaint();
parentPanel.revalidate();
}
});
card3Button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
parentPanel.removeAll();
parentPanel.add(card3Panel);
parentPanel.repaint();
parentPanel.revalidate();
}
});
效果演示
完整代码
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class CardLayout {
private JPanel mainPanel;
private JPanel buttonPanel;
private JButton card1button;
private JButton card2Button;
private JButton card3Button;
private JPanel card1Panel;
private JPanel card2Panel;
private JPanel parentPanel;
private JPanel card3Panel;
private JCheckBox checkBox1;
private JRadioButton radioButton1;
private JButton button1;
public CardLayout() {
card1button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
parentPanel.removeAll();
parentPanel.add(card1Panel);
parentPanel.repaint();
parentPanel.revalidate();
}
});
card2Button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
parentPanel.removeAll();
parentPanel.add(card2Panel);
parentPanel.repaint();
parentPanel.revalidate();
}
});
card3Button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
parentPanel.removeAll();
parentPanel.add(card3Panel);
parentPanel.repaint();
parentPanel.revalidate();
}
});
}
public static void main(String[] args) {
JFrame frame = new JFrame("Card Layout");
frame.setContentPane(new CardLayout().mainPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}