选择文件并显示图片代码:
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileFilter;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
class myFileFilter implements FileFilter{
@Override
public boolean accept(File pathname){
String filename=pathname.getName().toLowerCase();
if(filename.contains(".jpg")){
return false;
}else{
return true;
}
}
}
public class Myjava extends JFrame implements ActionListener{
private static final long serialVersionUID=1L;
JButton open=null;
JTextField jtfpath=null;
JLabel jlbImg=null;
JButton btnNext=null;
String strPath="";
String strFileName="";
File[] fileArray;
int NUM_IMG=0;
int index =0;
public static void main(String[] args){
new Myjava();
}
public Myjava(){
this.setTitle("Week16");
this.setLayout(new FlowLayout());
open=new JButton("选择目录");
open.addActionListener(this);
this.add(open);
jtfpath=new JTextField("选择的文件",40);
jtfpath.setEditable(false);
jtfpath.setHorizontalAlignment(JTextField.CENTER);
this.add(jtfpath);
btnNext=new JButton("显示下一张");
this.add(btnNext);
btnNext.addActionListener(this);
jlbImg=new JLabel();
jlbImg.setBackground(Color.red);
jlbImg.setBounds(100,100,200,200);
this.add(jlbImg);
this.setBounds(400,200,400,500);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
@Override
public void actionPerformed(ActionEvent e){
if(e.getSource()==open){
JFileChooser jfc=new JFileChooser();
jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
jfc.showDialog(new JLabel(),"查看");
File file=jfc.getSelectedFile();
if(file.isDirectory()){
System.out.println("文件夹:"+file.getAbsolutePath());
jtfpath.setText(file.getAbsolutePath());
}else if(file.isFile()){
System.out.println("文件:"+file.getAbsolutePath());
}System.out.println(jfc.getSelectedFile().getName());
jtfpath.setText(file.getAbsolutePath());
strPath=file.getAbsolutePath();
strFileName=jfc.getSelectedFile().getName();
if(file!=null && file.isDirectory()){
fileArray=file.listFiles();
NUM_IMG=fileArray.length;
}
}
if(e.getSource()==btnNext){
String strTmp=fileArray[index].toString();
index++;
if(index==NUM_IMG)
index=0;
jlbImg.setIcon(new ImageIcon(strTmp));
}
}
}