CardLayout佈局管理器
- CardLayout(卡片佈局管理器)能夠幫助用戶實現多個成員共享同一個顯示空間,並且一次只顯示一個容器組件的內容
- CardLayout佈局管理器將容器分爲很多層,每層的顯示空間佔據整個容器的大小,但是每層只允許放置一個容器的大小
CardLayout構造方法
- CardLayout():構造一個新佈局,默認間隔爲0
- CardLayout(int hgap,int vgap):創建佈局管理器,並指定組件的水平間隔(hgap)和垂直間隔(vgap)
CardLayout方法
- void first(Container parent):顯示parent容器的第一張卡片
- void last(Container parent):顯示parent容器的最後一張卡片
- void previous(Container parent):顯示parent容器的上一張卡片
- void next(Container parent):顯示parent容器的下一張卡片
- void show(Container parent,String name):顯示parent容器中名稱爲name的卡片,如果不存在,則不會發生任何操作
- 卡片佈局是連接的,當在最後一個面板使用next方法會返回到第一個,同理。在第一個面板使用previous會顯示最後一個面板
Demo
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class DemoCardLayout {
public static void main(String[] args) {
JFrame jFrame = new JFrame("CardLayout窗體");
Container container = jFrame.getContentPane();
JButton button1 = new JButton("上一個");
JButton button2 = new JButton("第2個");
JButton button3 = new JButton("下一個");
CardLayout cardLayout = new CardLayout();
//用於顯示
JPanel jPanel = new JPanel();
JPanel jPanelButton = new JPanel();
//設置顯示面板佈局爲卡片佈局
jPanel.setLayout(cardLayout);
//設置按鈕面板背景色
jPanelButton.setBackground(Color.DARK_GRAY);
//設置顯示面板和按鈕面板的佈局位置
container.add(jPanel,BorderLayout.CENTER);
container.add(jPanelButton,BorderLayout.SOUTH);
//把按鈕組件放進 jPanelButton面板
jPanelButton.add(button1);
jPanelButton.add(button2);
jPanelButton.add(button3);
//創建用於顯示的面板
JPanel jPanel1 = new JPanel();
JPanel jPanel2 = new JPanel();
JPanel jPanel3 = new JPanel();
//在每個字面板插入標籤
jPanel1.add(new JLabel("第一個card"));
jPanel2.add(new JLabel("第二個card"));
jPanel3.add(new JLabel("第三個card"));
//把三個字面板組件放進顯示面板
jPanel.add(jPanel1,"1");
jPanel.add(jPanel2,"2");
jPanel.add(jPanel3,"3");
//設置顯示面板佈局爲卡片佈局
button1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
cardLayout.previous(jPanel);
}
});
button2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
cardLayout.show(jPanel,"2");
}
});
button3.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
cardLayout.next(jPanel);
}
});
jFrame.setSize(400,400);
jFrame.setVisible(true);
jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
點擊下一個
點擊上一個
點擊第2個