CardLayout使用


相對於BoxLayout,GridBugLayut等常用的Swing layout,CardLayout是特殊的,前者是一個容器內布置組件,而后者是在一個容器內放置很多頁面(但一個時間只用顯示一個)。

比如需要制作Step by Step的桌面程序,使用CardLayout就非常方便快捷。下面用代碼說明:

JPanel innerPanel=new JPanel(new CardLayout());// 對容器innerPanel設置為CardLayout

// 用於初始化頁面和顯示頁面的一些字符串常量

private static final String WELCOME="welcome"; 
private static final String URL="url"; 
private static final String COUNT="count";

// 把歡迎頁加入innerPanel,WelcomePage繼承自JPanel,下類同
welcomePage=new WelcomePage("/welcome.jpg");
innerPanel.add(welcomePage,WELCOME);

// 把地址頁加入innerPanel
urlPage=new UrlPage();
innerPanel.add(urlPage,URL);

// 把數目頁加入innerPanel
countPage=new CountPage();
innerPanel.add(countPage,COUNT);

需要顯示某個頁面的話可以用下面的函數,pageName取值就是前面定義的"welcome","url","count"等。

// 顯示一個頁面
public void showPage(String pageName){
        CardLayout c=(CardLayout)(innerPanel.getLayout());
        c.show(innerPanel, pageName);
}

每當一個頁面被顯示出來,其它頁面就被遮擋了。要是不采用CardLayout而自己編碼,要多花些工夫.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM