CardLayout
类将容器中的每个组件排列为卡片。一次只能看到一张卡片,而容器则充当一叠卡片。
示例
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SwingTester {
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
private JLabel msglabel;
public SwingTester(){
prepareGUI();
}
public static void main(String[] args){
SwingTester swingLayoutDemo = new SwingTester();
swingLayoutDemo.showCardLayoutDemo();
}
private void prepareGUI(){
mainFrame = new JFrame("Java SWING CardLayout示例");
mainFrame.setSize(560,400);
mainFrame.setLayout(new GridLayout(3, 1));
headerLabel = new JLabel("",JLabel.CENTER );
statusLabel = new JLabel("",JLabel.CENTER);
statusLabel.setSize(350,100);
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showCardLayoutDemo(){
headerLabel.setText("Layout in action: CardLayout");
final JPanel panel = new JPanel();
panel.setBackground(Color.pink);
panel.setSize(300,300);
CardLayout layout = new CardLayout();
layout.setHgap(10);
layout.setVgap(10);
panel.setLayout(layout);
JPanel buttonPanel = new JPanel(new FlowLayout());
buttonPanel.add(new JButton("确定"));
buttonPanel.add(new JButton("取消"));
JPanel textBoxPanel = new JPanel(new FlowLayout());
textBoxPanel.add(new JLabel("名称:"));
textBoxPanel.add(new JTextField(20));
panel.add("Button", buttonPanel);
panel.add("Text", textBoxPanel);
final DefaultComboBoxModel panelName = new DefaultComboBoxModel();
panelName.addElement("Button");
panelName.addElement("Text");
final JComboBox listCombo = new JComboBox(panelName);
listCombo.setSelectedIndex(0);
JScrollPane listComboScrollPane = new JScrollPane(listCombo);
JButton showButton = new JButton("显示");
showButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = "";
if (listCombo.getSelectedIndex() != -1) {
CardLayout cardLayout = (CardLayout)(panel.getLayout());
cardLayout.show(panel,
(String)listCombo.getItemAt(listCombo.getSelectedIndex()));
}
statusLabel.setText(data);
}
});
controlPanel.add(listComboScrollPane);
controlPanel.add(showButton);
controlPanel.add(panel);
mainFrame.setVisible(true);
}
}
执行上面示例代码,得到以下结果: