转自:http://blog.csdn.net/mq612/article/details/1487648
Java中CardLayout卡片布局管理器使用的小例子
001 | import java.awt.BorderLayout; |
002 | import java.awt.CardLayout; |
003 | import java.awt.Color; |
004 | import java.awt.Insets; |
005 | import java.awt.event.ActionEvent; |
006 | import java.awt.event.ActionListener; |
007 | import javax.swing.JButton; |
008 | import javax.swing.JFrame; |
009 | import javax.swing.JLabel; |
010 | import javax.swing.JPanel; |
011 | import javax.swing.UIManager; |
014 | * Java中CardLayout布局管理器使用的小例子 |
016 | * @author 五斗米 <如转载请保留作者和出处> |
017 | * @blog http://blog.csdn.net/mq612 |
019 | public class TestMain extends JFrame { |
020 | private JPanel pane = null ; |
021 | private JPanel p = null ; |
022 | private CardLayout card = null ; |
023 | private JButton button_1 = null ; |
024 | private JButton button_2 = null ; |
025 | private JButton b_1 = null , b_2 = null , b_3 = null ; |
026 | private JPanel p_1 = null , p_2 = null , p_3 = null ; |
029 | super ( "CardLayout Test" ); |
032 | UIManager.setLookAndFeel( "com.sun.java.swing.plaf.windows.WindowsLookAndFeel" ); |
033 | } catch (Exception ex) { |
034 | ex.printStackTrace(); |
036 | /**创建一个具有指定的水平和垂直间隙的新卡片布局*/ |
037 | card = new CardLayout( 5 , 5 ); |
038 | pane = new JPanel(card); |
040 | button_1 = new JButton( "< 上一步" ); |
041 | button_2 = new JButton( "下一步 >" ); |
042 | b_1 = new JButton( "1" ); |
043 | b_2 = new JButton( "2" ); |
044 | b_3 = new JButton( "3" ); |
045 | b_1.setMargin( new Insets( 2 , 2 , 2 , 2 )); |
046 | b_2.setMargin( new Insets( 2 , 2 , 2 , 2 )); |
047 | b_3.setMargin( new Insets( 2 , 2 , 2 , 2 )); |
056 | p_1.setBackground(Color.RED); |
057 | p_2.setBackground(Color.BLUE); |
058 | p_3.setBackground(Color.GREEN); |
059 | p_1.add( new JLabel( "JPanel_1" )); |
060 | p_2.add( new JLabel( "JPanel_2" )); |
061 | p_3.add( new JLabel( "JPanel_3" )); |
065 | /**下面是翻转到卡片布局的某个组件,可参考API中的文档*/ |
066 | button_1.addActionListener( new ActionListener(){ |
067 | public void actionPerformed(ActionEvent e) { |
071 | button_2.addActionListener( new ActionListener(){ |
072 | public void actionPerformed(ActionEvent e) { |
076 | b_1.addActionListener( new ActionListener() { |
077 | public void actionPerformed(ActionEvent e) { |
078 | card.show(pane, "p1" ); |
081 | b_2.addActionListener( new ActionListener() { |
082 | public void actionPerformed(ActionEvent e) { |
083 | card.show(pane, "p2" ); |
086 | b_3.addActionListener( new ActionListener() { |
087 | public void actionPerformed(ActionEvent e) { |
088 | card.show(pane, "p3" ); |
091 | this .getContentPane().add(pane); |
092 | this .getContentPane().add(p, BorderLayout.SOUTH); |
093 | this .setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); |
094 | this .setSize( 300 , 200 ); |
095 | this .setVisible( true ); |
098 | public static void main(String[] args) { |