Crazy Java Practice 第3章 图片浏览器

package com.chenjo.viewer;

import javax.swing.JFrame;
/**
 * 图片浏览器入口类
 * @author chenjo
 *
 */
public class Main {
	public static void main(String args[]){
		ViewerFrame f = new ViewerFrame();
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
}

package com.chenjo.viewer;

import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.ImageIcon;

import com.chenjo.viewer.action.Action;
/**
 * 工具栏的Action类
 * 
 * @author chenjo
 *
 */
@SuppressWarnings("serial")
public class ViewerAction extends AbstractAction{
	private String actionName = "";
	private ViewerFrame frame = null;
	//此工具栏的AbstractAction所对应的com.chenjo.viewer.action包的某个Action实体
	private Action action = null;
	
	/**
	 * 构造器
	 * 
	 */	
	public ViewerAction(){
		// 调用父构造器
		super();
	}
	
	/**
	 * 构造器
	 * 
	 * @param icon
	 *            ImageIcon 图标
	 * @param name
	 *            Action 名称
	 */	
	public ViewerAction(ImageIcon icon, String actionName, ViewerFrame frame){
		// 调用父构造器
		super("", icon);
		this.actionName = actionName;
		this.frame = frame;
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		ViewerService service = ViewerService.getInstance();
		Action action = getAction(this.actionName);
		action.execute(service, frame);
	}
	/**
	 * 通过actionName得到该类的实例
	 * @param actionName
	 * @return
	 */
	private Action getAction(String actionName){
		try{
			if(this.action == null){
				//创建Action实例
				Action action = (Action)Class.forName(actionName).newInstance();
				this.action = action;
			}
			return this.action;
		}catch(Exception e){
			return null;
		}
	}
}

package com.chenjo.viewer;

import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;
import java.io.File;

/**
 * 文件选择器对话框
 * @author Jointech
 *
 */
public class ViewerFileChooser extends JFileChooser{
	/**
	 * 使用用户默认路径创建一个ImageFileChooser
	 */
	public ViewerFileChooser(){
		super();
		setAcceptAllFileFilterUsed(false);
		addFilter();
	}
	/**
	 * 使用自定义的路径路径创建一个ViewerFileChooser
	 * 
	 */
	public ViewerFileChooser(String currentDirectoryPath){
		super(currentDirectoryPath);
		setAcceptAllFileFilterUsed(false);
		addFilter();
	}
	/**
	 * 增加文件过滤器
	 */
	private void addFilter(){
		this.addChoosableFileFilter(new MyFileFilter(new String[] {".BMP"}, "BMP (*.BMP)"));
		this.addChoosableFileFilter(new MyFileFilter(new String[] {".JPG", ".JPEG", ".JPE", ".JFIF"}, "JPEG (*.JPG;*.JPEG;*.JPE;*.JFIF)"));
		this.addChoosableFileFilter(new MyFileFilter(new String[] {".GIF"}, "GIF (*.GIF)"));
		this.addChoosableFileFilter(new MyFileFilter(new String[] {".TIF", ".TIFF"}, "TIFF (*.TIF;*.TIFF)"));
		this.addChoosableFileFilter(new MyFileFilter(new String[] {".PNG"}, "PNG (*.PNG)"));
		this.addChoosableFileFilter(new MyFileFilter(new String[] {".ICO"}, "ICO (*.ICO)"));
		this.addChoosableFileFilter(new MyFileFilter(new String[] {".BMP",
				".JPG",".JPEG",".JPE",".JFIF",".GIF",".TIF", ".TIFF", 
				".PNG", ".ICO"}, "所有图形文件"));		
	}
	class MyFileFilter extends FileFilter{
		// 后缀名数组
		String[] suffArr;
		String description;
		public MyFileFilter(){
			super();
		}
		/**
		 * 用包含后缀名的数组与描述创建一个MyFileFilter
		 */
		public MyFileFilter(String[] suffArr, String description){
			super();
			this.suffArr = suffArr;
			this.description = description;				
		}
		/**
		 * 
		 */
		@Override
		public boolean accept(File f) {
			// 如果文件的后缀名合法,返回true
			for(String s : suffArr){
				if(f.getName().toUpperCase().endsWith(s)){
					return true;
				}
			}
			// 如果是目录,返回true, 否则返回false
			return f.isDirectory();
		}
		/**
		 * 获取描述信息
		 */
		@Override
		public String getDescription() {
			return this.description;
		}
		
	}	
}

package com.chenjo.viewer;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JToolBar;
import javax.swing.JButton;
import javax.swing.ImageIcon;
import javax.swing.JLabel;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.FlowLayout;
import java.awt.Dimension;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

/*
 * 主界面类
 * 
 */
@SuppressWarnings("serial")
public class ViewerFrame extends JFrame {
	// 设置读图区的宽和高
	private int width = 800;
	private int height = 600;
	// 用一个JLabel放置图片
	JLabel label = new JLabel();
	ViewerService service = ViewerService.getInstance();
	
	// 加给菜单的事件监听器
	ActionListener menuListener = new ActionListener(){
		public void actionPerformed(ActionEvent e){
			service.menuDo(ViewerFrame.this, e.getActionCommand());
		}
	};
	/**
	 * 构造器
	 */	
	public ViewerFrame(){
		super();
		// 初始化这个JFrame
		init();
	}
	public void init(){
		// 设置标题
		this.setTitle("看图程序");
		// 设置大小
		this.setPreferredSize(new Dimension(width, height));
		// 创建菜单
		createMenuBar();
		// 创建工具栏
		JPanel toolBar = createToolPanel();
		// 把工具栏和读图区加到JFrame里面
		this.add(toolBar, BorderLayout.NORTH);
		this.add(new JScrollPane(label), BorderLayout.CENTER);
		// 设置为可见
		this.setVisible(true);
		this.pack();
	}
	public JLabel getLabel(){
		return this.label;
	}
	/**
	 * 创建工具栏
	 * 
	 * @return JPanel
	 */
	public JPanel createToolPanel(){
		// 创建一个JPanel
		JPanel panel = new JPanel();
		// 创建一个标题为"工具"的工具栏
		JToolBar toolBar = new JToolBar("工具");
		// 设置为不可拖动
		toolBar.setFloatable(false);
		// 设置布局方式
		panel.setLayout(new FlowLayout(FlowLayout.LEFT));
		// 工具数组
		String[] toolArr = {"com.chenjo.viewer.action.OpenAction",
				"com.chenjo.viewer.action.LastAction",
				"com.chenjo.viewer.action.NextAction",
				"com.chenjo.viewer.action.BigAction",
				"com.chenjo.viewer.action.SmallAction"};
		for(int i=0; i<toolArr.length; i++){
			ViewerAction action = new ViewerAction(new ImageIcon("img/"
					+ toolArr[i] + ".gif"), toolArr[i], this);
			// 以图标创建一个新的button
			JButton button = new JButton(action);
			// 把button加到工具栏中
			toolBar.add(button);
		}
		panel.add(toolBar);
		return panel;
	}
	/**
	 * 创建菜单栏
	 */
	public void createMenuBar(){
		// 创建一个JMenuBar以放置菜单
		JMenuBar menuBar = new JMenuBar();
		// 菜单文字数组,以下面的menuItemArr一一对应
		String[] menuArr = {"文件(F)", "工具(T)", "帮助(H)"};
		// 菜单项文字数组
		String[][] menuItemArr = {{"打开(O)", "-", "退出(X)"}, {"放大(M)", "缩小(O)", "-", "上一个(X)", "下一个(P)"}, {"帮助主题", "关于"}};
		// 遍历menuArr与menuItemArr去创建菜单
		for(int i=0; i<menuArr.length; i++){
			// 新建一个JMenu菜单
			JMenu menu = new JMenu(menuArr[i]);
			for(int j=0; j<menuItemArr[i].length; j++){
				// 如果menuItemArr[i][j]等于"-"
				if(menuItemArr[i][j].equals("-")){
					// 设置菜单分隔
					menu.addSeparator();
				}else{
					// 新建一个JMenuItem菜单项
					JMenuItem menuItem = new JMenuItem(menuItemArr[i][j]);
					menuItem.addActionListener(menuListener);
					// 把菜单项加到JMenu菜单里面
					menu.add(menuItem);
				}
			}
			// 把菜单加到JMenuBar上
			menuBar.add(menu);
		}
		// 设置JMenubar
		this.setJMenuBar(menuBar);
	}
}

package com.chenjo.viewer;

import javax.swing.ImageIcon;
import java.awt.Image;
import java.io.File;
import javax.swing.filechooser.FileFilter;
import java.util.List;
import java.util.ArrayList;
/**
 * 图片浏览器业务类
 * @author Jointech
 *
 */
public class ViewerService {
	private static ViewerService service = null;
	// 新建一个ViewerFileChooser
	private ViewerFileChooser fileChooser = new ViewerFileChooser();
	// 放大或者缩小的比例
	private double range = 0.2;
	// 目前的文件夹
	private File currentDirectory = null;
	// 目前文件夹下的所有图片文件
	private List<File> currentFiles = null;
	// 目前图片文件
	private File currentFile = null;
	/*
	 * 私有构造器
	 */
	private ViewerService(){		
	}
	/**
	 * 获取单态实例
	 */
	public static ViewerService getInstance(){
		if(service == null){
			service = new ViewerService();
		}
		return service;
	}
	/**
	 * 
	 */
	public void open(ViewerFrame frame){
		// 如果选择打开
		if(fileChooser.showOpenDialog(frame) == ViewerFileChooser.APPROVE_OPTION){
			// 给目前打开的文件赋值
			this.currentFile = fileChooser.getSelectedFile();
			// 获取文件路径
			String name = this.currentFile.getPath();
			// 获取目前文件夹
			File cd = fileChooser.getCurrentDirectory();
			// 如果文件夹有改变
			if(cd != this.currentDirectory || this.currentDirectory == null){
				// 获取fileChooser的所有FileFilter
				FileFilter[] fileFilters = fileChooser.getChoosableFileFilters();
				File[] files = cd.listFiles();
				this.currentFiles = new ArrayList<File>();
				for(File file : files){
					for(FileFilter filter : fileFilters){
						if(filter.accept(file)){
							// 如果是图片文件不尚未存在于列表中
							if(!currentFiles.contains(file)){
								// 把文件加到currentFiles中
								this.currentFiles.add(file);
							}
						}
					}
				}
			}
			ImageIcon icon = new ImageIcon(name);
			frame.getLabel().setIcon(icon);
		}
	}	
		/**
		 * 
		 */
		public void zoom(ViewerFrame frame, boolean isEnlarge){
			// 获取放大或者缩小的乘比
			double enlargeRange = isEnlarge ? (1+range) : (1-range);
			// 获取目前的图片
			ImageIcon icon = (ImageIcon)frame.getLabel().getIcon();
			if(icon != null){
				// 获取改变大小后的图片
				int width = (int)(icon.getIconWidth() * enlargeRange);
				ImageIcon newIcon = new ImageIcon(icon.getImage()
						.getScaledInstance(width, -1, Image.SCALE_DEFAULT));
				// 改变显示的图片
				frame.getLabel().setIcon(newIcon);
			}
		}
		public void last(ViewerFrame frame){
			// 如果有打开包含图片的文件夹
			if(this.currentFiles != null && !this.currentFiles.isEmpty()){
				int index = this.currentFiles.indexOf(this.currentFile);
				// 打开上一个
				if(index > 0){
					File file = (File)this.currentFiles.get(index - 1);
					ImageIcon icon = new ImageIcon(file.getPath());
					frame.getLabel().setIcon(icon);
					this.currentFile = file;
					
				}
			}
		}
		public void next(ViewerFrame frame){
			// 如果有打开包含图片的文件夹
			if(this.currentFiles != null && !this.currentFiles.isEmpty()){
				int index = this.currentFiles.indexOf(this.currentFile);
				// 打开下一个
				if(index+1 < this.currentFiles.size()){
					File file = (File)this.currentFiles.get(index + 1);
					ImageIcon icon = new ImageIcon(file.getPath());
					frame.getLabel().setIcon(icon);
					this.currentFile = file;
				}
			}
			
		}
		/**
		 * 响应菜单的动作
		 * @param frame
		 * @param cmd
		 */
		public void menuDo(ViewerFrame frame, String cmd){
			if(cmd.equals("打开(O)")){
				open(frame);
			}
			if(cmd.equals("放大(M)")){
				zoom(frame, true);
			}
			if(cmd.equals("缩小(O)")){
				zoom(frame, false);
			}
			if(cmd.equals("上一个(X)")){
				last(frame);
			}
			if(cmd.equals("下一个(P)")){
				next(frame);
			}
			if(cmd.equals("退出(X)")){
				System.exit(0);
			}
		}
}

package com.chenjo.viewer.action;

import com.chenjo.viewer.ViewerFrame;
import com.chenjo.viewer.ViewerService;
/**
 * 图片浏览器的Action接口
 * @author Jointech
 *
 */
public interface Action {
	/**
	 * 具体执行的方法
	 * @param service 图片浏览器的业务处理类
	 * @param frame 主界面对象
	 */
	void execute(ViewerService service, ViewerFrame frame);
}

package com.chenjo.viewer.action;

import com.chenjo.viewer.ViewerFrame;
import com.chenjo.viewer.ViewerService;
/**
 * 放大图片的Action
 * @author Jointech
 *
 */
public class BigAction implements Action {

	@Override
	public void execute(ViewerService service, ViewerFrame frame) {
		service.zoom(frame, true);
	}
	
}

package com.chenjo.viewer.action;

import com.chenjo.viewer.ViewerFrame;
import com.chenjo.viewer.ViewerService;
/**
 * 上一张图片的Action
 * @author Jointech
 *
 */
public class LastAction implements Action {
	public void execute(ViewerService service, ViewerFrame frame){
		service.last(frame);
	}
}

package com.chenjo.viewer.action;

import com.chenjo.viewer.ViewerFrame;
import com.chenjo.viewer.ViewerService;
/**
 * 下一张图片的Action
 * @author Jointech
 *
 */
public class NextAction implements Action {

	@Override
	public void execute(ViewerService service, ViewerFrame frame) {
		service.next(frame);		
	}
}

package com.chenjo.viewer.action;

import com.chenjo.viewer.ViewerFrame;
import com.chenjo.viewer.ViewerService;
/**
 * 打开图片文件的Action
 * @author Jointech
 *
 */
public class OpenAction implements Action {
	public void execute(ViewerService service, ViewerFrame frame){
		service.open(frame);
	}
}

package com.chenjo.viewer.action;

import com.chenjo.viewer.ViewerFrame;
import com.chenjo.viewer.ViewerService;
/**
 * 缩小图片的Action
 * @author Jointech
 *
 */
public class SmallAction implements Action {

	@Override
	public void execute(ViewerService service, ViewerFrame frame) {
		service.zoom(frame, false);		
	}
}

你可能感兴趣的:(java)