本文实例讲述了Java编程使用卡片布局管理器。分享给大家供大家参考,具体如下:
运行效果:
完整示例代码:
package com.han; import java.awt.BorderLayout; import java.awt.CardLayout; import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingConstants; /** * 使用卡片布局管理器 * @author HAN * */ public class CardLayout_1 extends JFrame { /** * */ private static final long serialVersionUID = -5255525755443566487L; public CardLayout_1() { // TODO Auto-generated constructor stub Container container = getContentPane(); final CardLayout cardLayout = new CardLayout(); final JPanel cardPanel = new JPanel(cardLayout); String[] cardNames = { "卡片A", "卡片B", "卡片C" }; for (int i = 0; i < cardNames.length; i++) { // JLabel label = new JLabel(cardNames[i]); JLabel label = new JLabel(cardNames[i], SwingConstants.CENTER); // cardPanel.add(label); cardPanel.add(label, cardNames[i]); } container.add(cardPanel, BorderLayout.CENTER); JPanel buttonPanel = new JPanel(); // by default, the flow layout container.add(buttonPanel, BorderLayout.SOUTH); String[] buttonNames = { "第一个", "前一个", "卡片A", "卡片B", "卡片C", "后一个", "最后一个" }; for (int i = 0; i < buttonNames.length; i++) { final JButton button = new JButton(buttonNames[i]); buttonPanel.add(button); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub String buttonText = button.getText(); if (buttonText.equals("第一个")) { cardLayout.first(cardPanel); } else if (buttonText.equals("前一个")) { cardLayout.previous(cardPanel); } else if (buttonText.equals("卡片A")) { cardLayout.show(cardPanel, "卡片A"); } else if (buttonText.equals("卡片B")) { cardLayout.show(cardPanel, "卡片B"); } else if (buttonText.equals("卡片C")) { cardLayout.show(cardPanel, "卡片C"); } else if (buttonText.equals("后一个")) { cardLayout.next(cardPanel); }else { cardLayout.last(cardPanel); } } }); } } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub CardLayout_1 frame = new CardLayout_1(); frame.setTitle("www.jb51.net - 使用卡片布局管理器"); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); } }
更多关于java算法相关内容感兴趣的读者可查看本站专题:《Java数据结构与算法教程》、《Java操作DOM节点技巧总结》、《Java文件与目录操作技巧汇总》和《Java缓存操作技巧汇总》
希望本文所述对大家java程序设计有所帮助。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。