Java swing implements a simple picture browser

Re-open the book, see an example of a picture browser, run the code, re-understand the code, and paste the code directly

package awt;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;


public class ImageViewerFrame extends JFrame {
	private JLabel label;
	private JFileChooser chooser;
	private static final int DEFAULT_WIDTH = 500;
	private static final int DEFAULT_HEIGHT = 700;

	public ImageViewerFrame() {
		super();
		setTitle("图片浏览-lihm");
		setSize(this.DEFAULT_WIDTH,this.DEFAULT_HEIGHT);
		
		label = new JLabel();
		add(label);
		
		this.chooser = new JFileChooser();//java提供的文件选择器
		chooser.setCurrentDirectory(new File("."));//设置当前浏览路径
		
		JMenuBar menuBar = new JMenuBar();
		setJMenuBar(menuBar);
		
		JMenu menu = new JMenu("文件");
		menuBar.add(menu);
		
		JMenuItem openItem = new JMenuItem("打开图片");
		menu.add(openItem);
		
		openItem.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				int result = chooser.showOpenDialog(null);//弹出文件选择对话框
				if(result==JFileChooser.APPROVE_OPTION){
					String name = chooser.getSelectedFile().getPath();
					label.setIcon(new ImageIcon(name));
					
				}
				
			}
			
			
		});
		
		JMenuItem exitItem = new JMenuItem("退出");
		menu.add(exitItem);
		exitItem.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
			    System.exit(0);
			}
			
		});
	}


}


The class where the main method is located:

package awt;
/**
 * @author LIHM
 * @time 2013-01-20
 * @desc ImageViewer
 */
import java.awt.EventQueue;
import javax.swing.JFrame;

public class ImageViewer {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//EventQueue 是一个与平台无关的类,它将来自于基础同位体类和受信任的应用程序类的事件列入队列
		//invokeLater导致 runnable 的 run 方法在 EventQueue 的指派线程上被调用
		EventQueue.invokeLater(new Runnable(){//此处使用Runnable的一个匿名对象
			@Override
			public void run() {
				// TODO Auto-generated method stub
				JFrame frame = new ImageViewerFrame();
				frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
				frame.setVisible(true);
				
			}
			
		});

	}

}


The effect is as follows:

click menu

Click to open the image to open the file view of the directory where the class is located

After selecting the file it shows:

The program does not compress and read the picture, but only displays a corner of the picture, and more processing can be done later.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324062688&siteId=291194637