- Swing 程式設計例項
- 示例 - 主頁
- 示例 - 環境設定
- 示例 - 邊界
- 示例 - 按鈕
- 示例 - 複選框
- 示例 - 組合框
- 示例 - 顏色選擇器
- 示例 - 對話方塊
- 示例 - 編輯窗格
- 示例 - 檔案選擇器
- 示例 - 格式文字欄位
- 示例 - 框架
- 示例 - 列表
- 示例 - 佈局
- 示例 - 選單
- 示例 - 密碼欄位
- 示例 - 進度條
- 示例 - 滾動窗格
- 示例 - 滑塊
- 示例 - 旋轉器
- 示例 - 表格
- 示例 - 工具欄
- 示例 - 樹
- Swing 有用資源
- Swing - 快速指南
- Swing - 有用資源
- Swing - 討論
Swing 例項 - 卡片佈局
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 Examples");
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.CYAN);
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("OK"));
buttonPanel.add(new JButton("Cancel"));
JPanel textBoxPanel = new JPanel(new FlowLayout());
textBoxPanel.add(new JLabel("Name:"));
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("Show");
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);
}
}
輸出
swingexamples_layouts.htm
廣告