教育路上
摘要:java布局管理CardLayout,我們經常會通過選項卡按鈕來切換程序中的界面,這些界面就相當于一張張卡片,而管理這些卡片的布局管理器就是卡片布局管理器(CardLayout)。以下是我們為大家整理的,相信大家閱讀完后肯定有了自己的選擇吧。
2022-07-07 20:36網絡推薦
在操作程序時,我們經常會通過選項卡按鈕來切換程序中的界面,這些界面就相當于一張
張卡片,而管理這些卡片的布局管理器就是卡片布局管理器(CardLayout)??ㄆ季止芾砥鲗⒔缑?
看做一系列卡片,在任何時候只有其中一張卡片是可見的,這張卡片占據容器的整個區域。在
CardLayout 布局管理中經常會用到下面幾個方法,如表 11-4 所示。
-12 Example12.java;’
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
//定義 Cardlayout 繼承 Frame 類,實現 ActionListener 接口
class Cardlayout extends Frame implements ActionListener {
Button nextbutton,preButton;
Panel cardPanel = new Panel(); // 定義 Panel 面板放置卡片
Panel controlpaPanel = new Panel(); // 定義 Panel 面板放置按鈕
CardLayout cardLayout = new CardLayout();// 定義卡片布局對象
public Cardlayout() { // 定義構造方法,設置卡片布局管理器的
屬性
setSize(300, 200);
setVisible(true);
// 為窗口添加關閉事件監聽器
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
Cardlayout.this.dispose();
}
});
cardPanel.setLayout(cardLayout); // 設置 cardPanel 面板對象為卡片布局
// 在 cardPanel 面板對象中添加 3 個文本標簽
cardPanel.add(new Label("第一個界面", Label.CENTER));
cardPanel.add(new Label("第二個界面", Label.CENTER));
cardPanel.add(new Label("第三個界面", Label.CENTER));
// 創建兩個按鈕對象
nextbutton = new Button("下一張卡片");
preButton = new Button("上一張卡片");
// 為按鈕對象注冊監聽器
nextbutton.addActionListener(this);
preButton.addActionListener(this);
// 將按鈕添加到 controlpaPanel 中
controlpaPanel.add(preButton);
controlpaPanel.add(nextbutton);
// 將 cardPanel 面板放置在窗口邊界布局的中間,窗口默認為邊界布局
this.add(cardPanel, BorderLayout.CENTER);
// 將 controlpaPanel 面板放置在窗口邊界布局的南區,
this.add(controlpaPanel, BorderLayout.SOUTH);
}
// 下面的代碼實現了按鈕的監聽觸發,并對觸發事件做出相應的處理
public void actionPerformed(ActionEvent e) {
// 如果用戶單擊 nextbutton,執行的語句
if (e.getSource() == nextbutton) {
// 切換 cardPanel 面板中當前組件之后的一個組件,若當前組件為最后一個組件,則
顯示第一個組件。
cardLayout.next(cardPanel);
}
if (e.getSource() == preButton) {
// 切換 cardPanel 面板中當前組件之前的一個組件,若當前組件為第一個組件,則顯
示最后一個組件。
cardLayout.previous(cardPanel);
}
}
}
public class Example12 {
public static void main(String[] args) {
Cardlayout cardlayout = new Cardlayout();
}
}
編譯運行程序,生成的窗口如圖 11-21 所示
例 11-12 中,在頂層 Frame 容器采用 BorderLayout 布局 CENTER 區域和 SOUTH 區城分別
放置 cardPanel 和 controlpaPanel 面板其中 cardPanel 面板采用 CardLayout 中放置了兩個名布
局管理器,其中放置了三個 Label 標簽代表三張卡片, controlpaPanel 為“上一張卡片”和“下一張卡
片"的按鈕,通過點擊這兩個按鈕,會觸發按鈕的事件監聽器,調用 CardLayout 的 previous()和
next( )方法對 cardPanel 面板中的卡片進行切換。CardLayout 的優點是可以使兩個或更多的界面
共享一個顯示空間,某一時刻只有一個界面可見。
訪客的評論 2023/05/28 23:31
文中描述的是準確的嗎,如何報名!