爱玺玺

爱玺玺的生活日记本。wx:lb87626

java制作相册 重点理解this.getClass().getResources()

import java.awt.CardLayout;

import java.awt.GridLayout;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;


import javax.swing.ImageIcon;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JPanel;



public class CardPic  extends JFrame{

CardLayout cardPic=new CardLayout();

JPanel jp1=new JPanel();

JPanel jp2=new JPanel();

public static void main(String[] args){

        CardPic cp=new CardPic();

}

    public CardPic() {

jp1.setLayout(new GridLayout(2,1));

JButton jbp=new JButton("上一张");

JButton jbn=new JButton("下一张");

CardListener cl=new CardListener();

jbp.addActionListener(cl);

jbn.addActionListener(cl);

jp1.add(jbp);

jp1.add(jbn);

jp2.setLayout(cardPic);

//如果是dos命令运行图片文件夹images需要放到源码同级目录src里面

//如果是eclipse运行图片文件夹images需要放到编译后的文件class同级目录bin里面

//如果要用eclipse打包到jar里面,那么images需要放到项目根目录里面

//重点理解this.getClass().getResources()是从执行文件处获取根目录

JButton jpCard1=new JButton(new ImageIcon(this.getClass().getResource("/images/1.jpg")));

JButton jpCard2=new JButton(new ImageIcon(this.getClass().getResource("/images/2.jpg")));

JButton jpCard3=new JButton(new ImageIcon(this.getClass().getResource("/images/3.jpg")));

JButton jpCard4=new JButton(new ImageIcon(this.getClass().getResource("/images/4.jpg")));

JButton jpCard5=new JButton(new ImageIcon(this.getClass().getResource("/images/5.jpg")));

JButton jpCard6=new JButton(new ImageIcon(this.getClass().getResource("/images/6.jpg")));

jp2.add(jpCard1,"1");

jp2.add(jpCard2,"2");

jp2.add(jpCard3,"3");

jp2.add(jpCard4,"4");

jp2.add(jpCard5,"5");

jp2.add(jpCard6,"6");

this.add(jp1,"West");

this.add(jp2);

this.setSize(600, 400);

this.setResizable(false);

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//生成个ico

this.setIconImage(new ImageIcon(this.getClass().getResource("/images/ico.jpg")).getImage());

this.setVisible(true);

}

    

  //内部类监听器

  class CardListener implements ActionListener{

  public void actionPerformed(ActionEvent e) {

  if(e.getActionCommand().equals("上一张")){

  cardPic.previous(jp2);

  }else if(e.getActionCommand().equals("下一张")){

  cardPic.next(jp2);

  }

  }

  }    

}


发表评论:

Powered By Z-BlogPHP 1.4 Deeplue Build 150101

Copyright Your WebSite.Some Rights Reserved.

蜀ICP备11021721号-5