java中CardLayout的使用方法
生活随笔
收集整理的這篇文章主要介紹了
java中CardLayout的使用方法
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
import javax.swing.*;import java.awt.*;
import java.awt.event.*;public class Card extends JFrame{/** JFrame的布局管理器是BorderLayout*/JPanel p;//位于中心區(qū)域的面板JButton b1,b2,b3,b4;//位于南部區(qū)域的四個按鈕
JLabel l1,l2,l3,l4;CardLayout c;//設(shè)置面板p的布局
Card(String name){super(name);this.setVisible(true);this.setBounds(400,300,400,400);p = new JPanel();//實例化pc = new CardLayout();//實例化cp.setLayout(c);//設(shè)置面板p的布局為c,等價于p = new JPanel(c);//實例化4個按鈕和標簽b1 = new JButton("previous");b2 = new JButton("two");b3 = new JButton("three");b4 = new JButton("next");l1 = new JLabel("first card");l2 = new JLabel("second card");l3 = new JLabel("thirth card");l4 = new JLabel("fourth card");//實例化4個子面板并設(shè)定相應(yīng)背景顏色JPanel p1 = new JPanel();JPanel p2 = new JPanel();JPanel p3 = new JPanel();JPanel p4 = new JPanel(); p1.setBackground(Color.green);p2.setBackground(Color.pink);p3.setBackground(Color.orange);p4.setBackground(Color.lightGray);//把上面4個面板添加到中心面板p中,并把4個面板分別用編號為1,2,3,4代替p.add(p1,"1");p.add(p2,"2");p.add(p3,"3");p.add(p4,"4");//把4個標簽分別添加到4個子面板中
p1.add(l1);p2.add(l2);p3.add(l3);p4.add(l4);//實例化位于南部區(qū)域的面板,并添加4個按鈕JPanel psourth = new JPanel();psourth.add(b1);psourth.add(b2);psourth.add(b3);psourth.add(b4);//把p,psourth分別添加到本JFrame的中心區(qū)域和南部區(qū)域this.add(p);//等價于this.add(p,BorderLayout.CENTER); 因為默認是把組件添加到中部 this.add(psourth,BorderLayout.SOUTH);//為按鈕b1添加監(jiān)聽器,當(dāng)被按下時顯示面板p中的前一個子面板b1.addActionListener(new ActionListener(){@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubc.previous(p);//顯示p中的上一個面板
} });//為按鈕b2添加監(jiān)聽器,當(dāng)被按下時顯示面板p中的第2個子面板b2.addActionListener(new ActionListener(){@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubc.show(p, "2");//顯示p中代號為2的面板
} });//以下類推b3.addActionListener(new ActionListener(){@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubc.show(p, "3");} });b4.addActionListener(new ActionListener(){@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stub
c.next(p);} });//使用匿名內(nèi)部類為本Frame添加監(jiān)聽器,當(dāng)點擊關(guān)閉按鈕時結(jié)束程序this.addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e){System.exit(0);}});}public static void main(String[] args) {// TODO Auto-generated method stubnew Card("My Card");}}
?
??
運行結(jié)果:
?
?
轉(zhuǎn)載于:https://www.cnblogs.com/UUUP/p/3800843.html
總結(jié)
以上是生活随笔為你收集整理的java中CardLayout的使用方法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 移动app开发者必读:国内主要移动广告平
- 下一篇: PXE自动安装FreeBSD