首页 > 开发 > Java > 正文

Java编程使用卡片布局管理器示例【基于swing组件】

2024-07-13 10:17:30
字体:
来源:转载
供稿:网友

本文实例讲述了Java编程使用卡片布局管理器。分享给大家供大家参考,具体如下:

运行效果:

Java,卡片布局管理器,swing组件

完整示例代码:

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.vevb.com - 使用卡片布局管理器");    frame.setVisible(true);    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    frame.pack();  }}

希望本文所述对大家java程序设计有所帮助。


注:相关教程知识阅读请移步到JAVA教程频道。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表