62,614
社区成员
发帖
与我相关
我的任务
分享
package org.jun.image;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.Border;
public class ShowFileDialog extends JFrame {
static String filePath = null;// 图片路径
Image image = null;
boolean thread = false; // 线程控制
static ShowFileDialog dialog;
private JLabel label = null;
public ShowFileDialog() {
super("图片查看");
}
public void launchFrame() {
JButton jButt = new JButton("图片路径");
setLocation(200, 100);
setSize(600, 400);
add(jButt, BorderLayout.SOUTH); // 添加按钮
label = new JLabel();
label.setBackground(Color.BLACK);
label.setBounds(new Rectangle(0, 0, 100, 100));
dialog.add(label, BorderLayout.NORTH);
dialog.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jButt.addMouseListener(new MouseListener() { // 监听Mouse点击事件
public void mouseReleased(MouseEvent e) { // 鼠标放开时,
// 开始这里很正常,后来调试时不知道改了哪,只要选了一次文件,就会马上弹出个FileDialog的对话框
FileDialog fd = new FileDialog(dialog);
fd.setSize(400, 300);
fd.setVisible(true);
filePath = fd.getDirectory() + fd.getFile();
System.out.println(filePath);
new ImageThread("d").run();
dialog.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
}// end of class
);
this.setVisible(true);
}
public JLabel getLabel() {
return label;
}
public static void main(String[] args) {
dialog = new ShowFileDialog();
dialog.starts();
}
public void starts() {
dialog.launchFrame();
}
class ImageThread implements Runnable { // 另起线程,当filePath改变时显示图片
private String s;
public ImageThread(String s) {
this.s = s;
}
public void run() {
if (true && filePath != null) {
Image image = null;
try {
image = ImageIO.read(new File(filePath));
} catch (IOException ex) {
System.out.println("文件路径错误");
}
getLabel().setIcon(new ImageIcon(image));
dialog.setVisible(true);
pack();
}
}
}
}