📄 drawandview.java
字号:
/* drawAndView.java 05/05/18 author 0324634 冯甲策 */
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.geom.*;
import javax.swing.filechooser.FileFilter;
import java.io.*;
import java.awt.image.*;
import javax.imageio.*;
import javax.imageio.stream.*;
//主框架类
class drawAndViewFrame extends JFrame {//主类是继承JFrame
public drawAndViewFrame() {
setTitle("drawAndView");//至窗口抬头
setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT);
panel = new drawAndViewPanel();//创建画图面板
openDialog = new JFileChooser();//建立文件选择器对象
saveDialog = new JFileChooser();
ExtensionFileFilter filter = new ExtensionFileFilter(); // 添加文件过滤器
filter.addExtension("jpg");//所过滤文件对象扩展名
filter.addExtension("gif");
filter.addExtension("png");
filter.addExtension("bmp");
filter.setDescription("其它图片文件('.jpg','.gif','.png','.bmp')");
openDialog.addChoosableFileFilter(filter);
saveDialog.addChoosableFileFilter(filter);
filter = new ExtensionFileFilter();
filter.addExtension("dif");
filter.setDescription("Draw画图文件('.dif')");
openDialog.addChoosableFileFilter(filter);
saveDialog.addChoosableFileFilter(filter);
JMenu fileMenu = new JMenu("文件"); //文件菜单
fileMenu.setMnemonic('F');//快捷键
JMenuItem newItem = new JMenuItem(newAction);
newItem.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_N, InputEvent.CTRL_MASK));//组合键新建
newItem.setMnemonic('N');
fileMenu.add(newItem);
openItem= new JMenuItem(openAction);
openItem.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_O, InputEvent.CTRL_MASK));//组合键打开
openItem.setMnemonic('O');
fileMenu.add(openItem);
saveItem= new JMenuItem(saveAction);
saveItem.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_S, InputEvent.CTRL_MASK));//组合键保存
saveItem.setMnemonic('S');
fileMenu.add(saveItem);
fileMenu.addSeparator();//分隔线
JMenuItem exitItem= new JMenuItem(exitAction);
exitItem.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_E, InputEvent.CTRL_MASK));//退出
exitItem.setMnemonic('E');
fileMenu.add(exitItem);
JMenuBar menuBar = new JMenuBar();//菜单条
setJMenuBar(menuBar);
menuBar.add(fileMenu);
Container contentPane=getContentPane();
contentPane.add(panel);
}
private void newFile()
{
panel.newImage();
currentFilePath = null;
}
private Action newAction = new
AbstractAction ("新建"){
public void actionPerformed(ActionEvent event)
{
newFile();
}
};
private void openFile()
{
if(currentFilePath==null)
openDialog.setCurrentDirectory(new File("."));
else openDialog.setCurrentDirectory(new File(currentFilePath));
System.out.println("This is openFile");
int result = openDialog.showOpenDialog(drawAndViewFrame.this);
if(result == JFileChooser.APPROVE_OPTION)//对于选中的文件
{
String name = openDialog.getSelectedFile().getPath().toLowerCase();
currentFilePath = name;
ArrayList<VImage> array=null;
Image image=null;
if(name.endsWith(".dif"))//后缀为.dif
{
ObjectInputStream in=null;
try
{
File f=new File(name);
in=new ObjectInputStream(new FileInputStream(f));
array=(ArrayList<VImage>)in.readObject();
in.close();
}catch(Exception e){
e.printStackTrace();
}
}else if(name.endsWith(".jpg")||name.endsWith(".gif")||name.endsWith(".png")||name.endsWith(".bmp"))
{
image=Toolkit.getDefaultToolkit().getImage(name);
if(image==null)
System.out.println("Wrong in read!");
}
if(array!=null)
System.out.println("Open file success and the size is"+array.size());
else if(image!=null)
System.out.println("Open file 图片");
panel.openImage(array,image);
if(!currentFilePath.endsWith(".dif"))
currentFilePath=null;
}
}
private Action openAction = new
AbstractAction ("打开...")
{
public void actionPerformed(ActionEvent event)
{
openFile();
}
};
private void saveFile()
{
ObjectOutputStream out=null;
if(currentFilePath==null)
{
int r = saveDialog.showSaveDialog(drawAndViewFrame.this);
if(r == JFileChooser.APPROVE_OPTION)
{
try
{
File file = saveDialog.getSelectedFile();
currentFilePath = file.getPath();
if (!file.exists())
{ file.createNewFile(); }
}
catch(IOException e)
{ e.printStackTrace(); }
}
}
if(currentFilePath==null) return;
try
{
if(currentFilePath.endsWith(".dif"))
{
Image i=panel.getBackgrand();//将图片设置为背景
if(i!=null)
{
JOptionPane.showMessageDialog(this, "can not save!");
currentFilePath=null;
return;
}
try
{
out=new ObjectOutputStream(new FileOutputStream(currentFilePath));
}catch(FileNotFoundException e){}
ArrayList a=panel.getImageArray();
if(a!=null)
System.out.println("Save file success and the size is"+a.size());
out.writeObject(a);
out.close();
}else if(currentFilePath.endsWith(".jpg")||currentFilePath.endsWith(".gif")||currentFilePath.endsWith(".png")||currentFilePath.endsWith(".bmp"))
{
String suf=null;
Iterator iter0 = writerFormats.iterator();
final String formatName = (String)iter0.next();
Iterator iter = ImageIO.getImageWritersByFormatName(formatName);
ImageWriter writer = (ImageWriter)iter.next();
BufferedImage a=panel.getPicture();
if(a==null) return;
if(writer!=null)
System.out.println("Right!");
File f = new File(currentFilePath);
try
{
ImageOutputStream imageOut
= ImageIO.createImageOutputStream(f);
writer.setOutput(imageOut);
writer.write(new IIOImage(a, null, null));
writer.dispose();
System.out.println("Success!");
}
catch (IOException exception)
{
JOptionPane.showMessageDialog(this, exception);
}
}
}catch(IOException e){}
}
private Action saveAction = new
AbstractAction ("保存")
{
public void actionPerformed(ActionEvent event)
{
saveFile();
}
};
public static Set getWriterFormats()
{
TreeSet writerFormats = new TreeSet();
TreeSet formatNames = new TreeSet(Arrays.asList(
ImageIO.getWriterFormatNames()));
while (formatNames.size() > 0)
{
String name = (String)formatNames.iterator().next();
Iterator iter = ImageIO.getImageWritersByFormatName(
name);
ImageWriter writer = (ImageWriter)iter.next();
String[] names = writer.getOriginatingProvider()
.getFormatNames();
writerFormats.add(names[0]);
formatNames.removeAll(Arrays.asList(names));
}
return writerFormats;
}
private Action exitAction = new AbstractAction("退出") // 退出 菜单项
{
public void actionPerformed(ActionEvent event)
{ System.exit(0); }
};
private drawAndViewPanel panel=null;
public static final int DEFAULT_WIDTH = 800;//窗口宽
public static final int DEFAULT_HEIGHT = 450;//窗口高
private String currentFilePath ; // 当前编辑文件的路径
private JMenuItem saveItem; // 保存菜单项
private JMenuItem openItem; // 打开菜单项
private static Set<String> writerFormats = getWriterFormats();
private final JFileChooser saveDialog; // 保存对话框
private final JFileChooser openDialog; // 打开对话框
}//画图板块
class ExtensionFileFilter extends FileFilter//附属类 文件扩展名过滤器
{
public void addExtension(String extension)
{
if (!extension.startsWith("."))
extension = "." + extension;
extensions.add(extension.toLowerCase());
}
public void setDescription(String aDescription)
{
description = aDescription;
}
public String getDescription()
{
return description;
}
public boolean accept(File f)
{
if (f.isDirectory()) return true;
String name = f.getName().toLowerCase();
for (int i = 0; i < extensions.size(); i++)
if (name.endsWith((String)extensions.get(i))) return true;
return false;//扩展名正确的返回真,否则为假
}
private String description = "";
private ArrayList extensions = new ArrayList();
}
class drawAndViewPanel extends JPanel implements ActionListener//监听器接口
{
public int toDraw;//画图类型
public Point2D p1;//直线
public boolean isFill;//是否填充
public Color color;//颜色
public boolean isSquare;//是否是圆形或正方形
private drawAndViewField drawField;
private JRadioButton fill;
private JRadioButton draw;
public drawAndViewPanel()
{
setLayout(new BorderLayout());//边框布局
JToolBar buttonPane=new JToolBar();//添加工具栏的中按钮(直线,椭圆,矩形,任意画)
JButton lbutton=new JButton("直线");
buttonPane.add(lbutton);
lbutton.addActionListener(this);//监听器注册
lbutton.setActionCommand("Line");//命令按钮
JButton ebutton=new JButton("椭圆");//添加各种按钮
buttonPane.add(ebutton);
ebutton.addActionListener(this);
ebutton.setActionCommand("Ellipse");
JButton rbutton=new JButton("矩形");
buttonPane.add(rbutton);
rbutton.addActionListener(this);
rbutton.setActionCommand("Rectangle");
JButton fbutton =new JButton("任意画");
buttonPane.add(fbutton);
fbutton.addActionListener(this);
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -