java图片的自定义切换


 private final int SUMGIF = 5;
 private CardLayout cardLayout=new CardLayout(20,10);
 private JButton first,next,last,previous;
 private JComboBox button;
 private JPanel cardPanel= new JPanel(cardLayout);
 myFrame(){
  super();
  setSize(500,500);
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  Border border=BorderFactory.createLineBorder(Color.RED,10);//设置卡片面板边框颜色;
  cardPanel.setBorder(border);
  setResizable(false);//设置窗口大小不可改变;
   for(int i=1;i<=SUMGIF;++i){
//    URL url=myFrame.class.getResource("image1.gif");
  JLabel labelGif = new JLabel(new ImageIcon("image"+i+".gif"));//为标签添加图像
  //JLabel labelGif = new JLabel(new ImageIcon("./src/image1.gif"));//为标签添加图像
  //JLabel labelGif = new JLabel(new ImageIcon("./src/image1.gif"));
  cardPanel.add(labelGif,String.valueOf(i));
 }
     JPanel buttonPanel = new JPanel();
     buttonPanel.add(first = new JButton("first"));
     first.setToolTipText("赵云出师");
     buttonPanel.add(previous = new JButton("previous"));
     buttonPanel.add(next = new JButton("next"));
     buttonPanel.add(last = new JButton("last"));
     buttonPanel.add(new JLabel("图像选择"));
     buttonPanel.add(button = new JComboBox());// buttonPanel.add(button);此句将引发 button.addItem(String.valueOf(i))空指针异常,无实例化JComboBox
     for(int i=1;i<=SUMGIF;++i)
         button.addItem(String.valueOf(i));            //为复选框添加子件;
  
     //将JPanel组件添加到JFrame中;
     getContentPane().add(cardPanel,BorderLayout.CENTER);
     getContentPane().add(buttonPanel,BorderLayout.SOUTH);
    //为个按钮添加监听事件;
     first.addActionListener(this);
     previous.addActionListener(this);
     last.addActionListener(this);
     next.addActionListener(this);
     button.addItemListener( this);
 }
 public void actionPerformed(ActionEvent e){
  if((JButton)e.getSource()==first)
   cardLayout.first(cardPanel);
     if((JButton)e.getSource()==last)
   cardLayout.last(cardPanel);
     if((JButton)e.getSource()==previous)
   cardLayout.previous(cardPanel);
     if((JButton)e.getSource()==next)
   cardLayout.next(cardPanel);
  }
 public static void main(String[]args){
  myFrame card = new myFrame();
  card.setVisible(true);
 }
 @Override
 public void itemStateChanged(ItemEvent e) {
  if(e.getSource()==button){// TODO Auto-generated method stub
   cardLayout.show(cardPanel, String.valueOf(e.getItem()));
  }
  
 }
 }
原文链接: http://blog.csdn.net/weiyirong/article/details/6668535

转载于:https://my.oschina.net/chen106106/blog/50794

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值