因此,您可以看到我的绘画程序正常运行。它可以绘制像椭圆形和矩形的形状(椭圆形看起来有点像,如果有人可以帮我修复它)。我想知道如何制作一个保存按钮。现在,我甚至不知道我在做什么。我一直在研究如何保存绘制的图像,但互联网上的代码都没有一个带有保存功能的java制作绘图程序的例子。所以这是我的代码:
Shapeframe类
package com.comp2526.assign2c.a.a00892238;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Event;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.FileWriter;
import javax.imageio.ImageIO;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JToolBar;
import javax.swing.KeyStroke;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
/**
* This class creates the painting program's toolbar, buttons and stuffs.
* @author Fu Han
* @version 1.0
*/
public class ShapeFrame extends JFrame implements ActionListener {
/**
* the white board
*/
static DrawPad drawboard;
/**
* the constant string 'save'.
*/
static final private String SAVE = "Save";
/**
* the constant string 'save as'.
*/
static final private String SAVE_AS = "Save As";
/**
* the constant string 'new'.
*/
static final private String NEW = "New";
/**
* the constant string 'color'.
*/
static final private String color = "Color";
/**
* string oval for easy access for buttons.
*/
static String oval = new String("oval");
/**
* string line for easy access for buttons.
*/
static String line = new String("line");
/**
* string rectangle for easy access for buttons.
*/
static String rectangle = new String("rectangle");
/**
* string square for easy access for buttons.
*/
static String square = new String("square");
/**
* color.
*/
Color currentColor;
/**
* ShapeFrame constructor.
*/
public ShapeFrame(){
super();
}
/**
* method that add buttons.
* @param toolBar Jtoolbar.
* @param btn Jbuttons.
*/
protected void addButtons(JToolBar toolBar, JButton btn) {
toolBar.add(btn);
}
/**
* method that add radio buttons.
* @param toolBar Jtoolbar.
* @param btn JRadioButton.
*/
protected void addRadioButtons(JToolBar toolBar, JRadioButton btn) {
toolBar.add(btn);
}
/**
* method that creates button.
* @param btnNam button name.
* @param actionCommand calling from string constant.
* @param toolTipText the message that will appear if cursor was hover over.
* @param altText alternative text.
* @return button Jbutton.
*/
protected JButton btnmaker(String btnNam, String actionCommand, String toolTipText, String altText) {
//Create and initialize the button.
JButton button = new JButton(btnNam);
button.setActionCommand(actionCommand);
button.setToolTipText(toolTipText);
button.addActionListener(this);
return button;
}
/**
* action performed when clicked button.
* @param e mouse click.
*/
public void actionPerformed(ActionEvent e) {
}
public static void savebtn(DrawPad dp) {
DrawPad dp1 = dp;
//String sb = "gg";
/*
public void save() throws IOException{
ImageIO.write(paintImage, "PNG", new File("filename.png"));
}*/
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new File("/home/me/Documents"));
int retrieval = chooser.showSaveDialog(null);
if (retrieval == JFileChooser.APPROVE_OPTION) {
try {
//FileWriter fw = new FileWriter(chooser.getSelectedFile()+".png");
//fw.write(sb.toString());
//fw.close();
ImageIO.write((RenderedImage) dp1.image, "PNG", new File("filename.png"));
ImageIo.
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
/**
* editlistener for menu bar.
* @author Fu Han
*
*/
private class EditListener implements ActionListener {
/**
* action performed when clicking menu button.
* @param e mouse click.
*/
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand() == SAVE) {
System.out.print("save");
}else{
System.out.println(e.getActionCommand());
}
}
}
/**
* radio listener for the radio buttons.
* @author Fu Han
*
*/
private class RadioListener implements ActionListener{
/**
* action performed when click the button.
* @param e mouse click.
*/
public void actionPerformed(ActionEvent e) {
System.out.print("ActionEvent received: ");
if (e.getActionCommand() == oval) {
System.out.println(oval + " pressed.");
drawboard.line = false;
drawboard.rectangle = false;
drawboard.square = false;
drawboard.oval = true;
}else if(e.getActionCommand() == rectangle){
System.out.println(rectangle + " pressed.");
drawboard.line = false;
drawboard.rectangle = true;
drawboard.square = false;
drawboard.oval = false;
}else if(e.getActionCommand() == square){
System.out.println(square + " pressed.");
drawboard.line = false;
drawboard.rectangle = false;
drawboard.square = true;
drawboard.oval = false;
}else{
System.out.println(line + " pressed.");
drawboard.line = true;
drawboard.rectangle = false;
drawboard.square = false;
drawboard.oval = false;
}
}
}
/**
* method for when changes of states that happened after clicking.
* @param e mouse click.
*/
public void stateChanged(ChangeEvent e) {
}
/**
* method for selecting color.
*/
private void selectColor(){
Color newColor = JColorChooser.showDialog(
ShapeFrame.this,
"Choose New Background Color",
currentColor);
if(newColor != null){
currentColor = newColor;
}
}
/**
* GUI initialization.
*/
public void init(){
Container content = getContentPane();
//Creates a new container
content.setLayout(new BorderLayout());
//sets the layout
final DrawPad drawPad = new DrawPad();
//creates a new padDraw, which is pretty much the paint program
content.add(drawPad, BorderLayout.CENTER);
JMenuBar menubar = new JMenuBar();
EditListener l = new EditListener();
JMenu filem = new JMenu("File");
JMenuItem mi;
mi = filem.add(new JMenuItem("New", 'n'));
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, Event.CTRL_MASK));
mi.addActionListener(l);
mi = filem.add(new JMenuItem("Open", 'o'));
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, Event.CTRL_MASK));
mi.addActionListener(l);
mi = filem.add(new JMenuItem("Save", 's'));
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, Event.CTRL_MASK));
mi.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
savebtn(drawPad);
}
});
mi = filem.add(new JMenuItem("Save As", 'a'));
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Y, Event.CTRL_MASK));
mi.addActionListener(l);
mi = filem.add(new JMenuItem("Exit", 'e'));
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, Event.CTRL_MASK));
mi.addActionListener(l);
JMenu shapem = new JMenu("Shape");
JMenuItem smi;
smi = shapem.add(new JMenuItem("Line", 'l'));
smi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, Event.CTRL_MASK));
smi.addActionListener(l);
smi = shapem.add(new JMenuItem("Circle", 'c'));
smi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, Event.CTRL_MASK));
smi.addActionListener(l);
smi = shapem.add(new JMenuItem("Rectangle", 'r'));
smi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_U, Event.CTRL_MASK));
smi.addActionListener(l);
smi = shapem.add(new JMenuItem("Square", 'q'));
smi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_I, Event.CTRL_MASK));
smi.addActionListener(l);
smi = shapem.add(new JMenuItem("Shape Picker", 'p'));
smi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, Event.CTRL_MASK));
smi.addActionListener(l);
menubar.add(filem);
menubar.add(shapem);
menubar.add(Box.createHorizontalGlue());
setJMenuBar(menubar);
//Create the toolbar.
JPanel panel = new JPanel();
JPanel panel2 = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
panel2.setLayout(new BoxLayout(panel2, BoxLayout.Y_AXIS));
JButton saveBtn = btnmaker("Save",SAVE, "save your paint", "Save");
JButton saveAsBtn = btnmaker("Save As",SAVE_AS, "save your paint to?","Save As");
JButton NewBtn = btnmaker("New",NEW,"new paint","New");
JButton colorbtn = btnmaker("Color",color,"choose color","Color");
colorbtn.setToolTipText("Click this button to select colors.");
colorbtn.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg) {
selectColor();
drawPad.color(currentColor);
}
});
RadioListener myListener = new RadioListener();
JRadioButton ovalShape = new JRadioButton(oval);
ovalShape.addActionListener(myListener);
ovalShape.setMnemonic(KeyEvent.VK_A);
ovalShape.setActionCommand(oval);
//add(ovalShape);
JRadioButton rectangleShape = new JRadioButton(rectangle);
rectangleShape.addActionListener(myListener);
rectangleShape.setMnemonic(KeyEvent.VK_A);
rectangleShape.setActionCommand(rectangle);
//add(rectangleShape);
JRadioButton squareShape = new JRadioButton(square);
squareShape.addActionListener(myListener);
squareShape.setMnemonic(KeyEvent.VK_A);
squareShape.setActionCommand(square);
//add(squareShape);
JRadioButton lineShape = new JRadioButton(line);
lineShape.addActionListener(myListener);
lineShape.setMnemonic(KeyEvent.VK_B);
lineShape.setActionCommand(line);
lineShape.setSelected(true);
//add(lineShape);
ButtonGroup group = new ButtonGroup();
group.add(ovalShape);
group.add(lineShape);
group.add(rectangleShape);
group.add(squareShape);
JToolBar toolBar = new JToolBar("File");
JToolBar toolBar2 = new JToolBar("Shape",JToolBar.VERTICAL);
JToolBar toolbar3 = new JToolBar("colors",JToolBar.VERTICAL);
addButtons(toolBar,saveBtn);
addButtons(toolBar,saveAsBtn);
addButtons(toolBar,NewBtn);
addRadioButtons(toolBar2,ovalShape);
addRadioButtons(toolBar2,lineShape);
addRadioButtons(toolBar2,rectangleShape);
addRadioButtons(toolBar2,squareShape);
addButtons(toolbar3,colorbtn);
panel.add(toolBar);
panel2.add(toolBar2);
panel2.add(toolbar3);
content.add(panel, BorderLayout.NORTH);
content.add(panel2, BorderLayout.WEST);
}
}
DrawPad类:
package com.comp2526.assign2c.a.a00892238;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.util.ArrayList;
import javax.swing.JComponent;
/**
* the draw pad class for drawing
* @author Fu Han
* @version 1.0
*/
class DrawPad extends JComponent{
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* image
*/
Image image;
/**
* what user will be using to draw on
*/
Rectangle r = null;
Oval o = null;
Graphics2D graphics2D;
ArrayList<Rectangle> rectangleList = null;
/**
*mouse coordinates
*/
static boolean rectangle = false;
static boolean oval = false;
static boolean line = false;
static boolean square = false;
int currentX, currentY, oldX, oldY;
/**
* shape object
*/
/**
* constructor
*/
public DrawPad(){
rectangleList = new ArrayList<Rectangle>();
setDoubleBuffered(false);
addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e){
oldX = e.getX();
oldY = e.getY();
if(rectangle == true){
r = new Rectangle(e.getX(), e.getY(),
e.getX(), e.getY(), graphics2D.getColor());
}else if(oval == true){
o = new Oval(e.getX(), e.getY(),
e.getX(), e.getY(), graphics2D.getColor());
}
}
});
//if the mouse is pressed it sets the oldX & oldY
//coordinates as the mouses x & y coordinates
addMouseMotionListener(new MouseMotionAdapter(){
public void mouseDragged(MouseEvent e){
currentX = e.getX();
currentY = e.getY();
if(graphics2D != null){
if(rectangle == true){
r = new Rectangle(r.getX1(),
r.getY1(), e.getX(), e.getY(),
r.getColor());
drawRectangle(r,graphics2D);
rectangleList.add(new Rectangle(r.getX1(),
r.getY1(), e.getX(), e.getY(),
graphics2D.getColor()));
repaint();
oval = false;
line = false;
square = false;
}
else if(line == true){
graphics2D.drawLine(oldX, oldY, currentX, currentY);
repaint();
oldX = currentX;
oldY = currentY;
rectangle = false;
oval = false;
square = false;
}
else if(oval == true){
o = new Oval(o.getX1(), o.getY1(),
e.getX(), e.getY(), o.getColor());
drawOval(o,graphics2D);
repaint();
rectangle = false;
square = false;
line = false;
}
}
}
});
//while the mouse is dragged it sets currentX & currentY as the mouses x and y
//then it draws a line at the coordinates
//it repaints it and sets oldX and oldY as currentX and currentY
}
/**
* painting dot
* @param g Graphic
*/
public void paintComponent(Graphics g){
if(image == null){
image = createImage(getSize().width, getSize().height);
graphics2D = (Graphics2D)image.getGraphics();
graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
clear();
}
g.drawImage(image, 0, 0, null);
}
public void clear(){
graphics2D.setPaint(Color.white);
graphics2D.fillRect(0, 0, getSize().width, getSize().height);
graphics2D.setPaint(Color.black);
repaint();
}
public void drawRectangle(Rectangle rek, Graphics gr) {
Graphics2D g = null;
if (gr instanceof Graphics2D) {
g = (Graphics2D) gr;
}
else{ return; }
//g.setStroke(new BasicStroke(3));
g.drawRect(rek.getX1(), rek.getY1(), rek.getWidth(), rek.getHeight());
g.setColor(graphics2D.getColor());
g.fillRect(rek.getX1(), rek.getY1(), rek.getWidth(), rek.getHeight());
//g.drawLine(rek.getX1(), rek.getY1(), rek.getX2(), rek.getY1());
//g.drawLine(rek.getX1(), rek.getY1(), rek.getX1(), rek.getY2());
//g.drawLine(rek.getX2(), rek.getY2(), rek.getX2(), rek.getY1());
// g.drawLine(rek.getX2(), rek.getY2(), rek.getX1(), rek.getY2());
}
public void drawOval(Oval ovo, Graphics gr) {
Graphics2D g = null;
if (gr instanceof Graphics2D) {
g = (Graphics2D) gr;
}
else{ return; }
//g.setStroke(new BasicStroke(3));
g.drawOval(ovo.getX1(), ovo.getY1(), ovo.getWidth(), ovo.getHeight());
g.setColor(graphics2D.getColor());
g.fillOval(ovo.getX1(), ovo.getY1(), ovo.getWidth(), ovo.getHeight());
//g.drawLine(rek.getX1(), rek.getY1(), rek.getX2(), rek.getY1());
//g.drawLine(rek.getX1(), rek.getY1(), rek.getX1(), rek.getY2());
//g.drawLine(rek.getX2(), rek.getY2(), rek.getX2(), rek.getY1());
// g.drawLine(rek.getX2(), rek.getY2(), rek.getX1(), rek.getY2());
}
/**
* setting dot color
* @param color color
*/
public void color(Color color){
graphics2D.setPaint(color);
repaint();
}
}
主要课程:
package com.comp2526.assign2c.a.a00892238;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Toolkit;
import javax.swing.JFrame;
/**
* main class.
* @author Fu Han
* @version 1.0
*
*/
public class Main {
/**
* tookit
*/
private static final Toolkit TOOLKIT;
static {
TOOLKIT = Toolkit.getDefaultToolkit();
}
/**
* defaulth constructor.
*/
private Main() {}
/**
* main method.
* @param argv argv
*/
public static void main(final String[] argv) {
final ShapeFrame frame;
frame = new ShapeFrame();
position(frame);
frame.init();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
/**
* position for shapeframe.
* @param frame Shapeframe.
*/
private static void position(final JFrame frame) {
final Dimension size;
size = calculateScreenArea(0.80f,
0.80f);
frame.setSize(size);
frame.setLocation(centreOnScreen(size));
}
/**
* the amount of center on screen
* @param size space size.
* @return the complete calculated space.
*/
public static Point centreOnScreen(final Dimension size) {
final Dimension screenSize;
if (size == null) {
throw new IllegalArgumentException("Size cannot be null");
}
screenSize = TOOLKIT.getScreenSize();
return (new Point((screenSize.width - size.width) / 2, (screenSize.height - size.height) / 2));
}
/**
* method that calculating screen area.
* @param widthPercent width percentage.
* @param heightPercent height percentage.
* @return dimension the dimension.
*/
public static Dimension calculateScreenArea(final float widthPercent,
final float heightPercent) {
final Dimension screenSize;
final Dimension area;
final int width;
final int height;
final int size;
if ((widthPercent <= 0.0f) || (widthPercent > 100.0f)) {
throw new IllegalArgumentException("widthPercent cannot be " +
"<= 0 or > 100 - got: " +
widthPercent);
}
if ((heightPercent <= 0.0f) || (heightPercent > 100.0f)) {
throw new IllegalArgumentException("heightPercent cannot be " +
"<= 0 or > 100 - got: " +
heightPercent);
}
screenSize = TOOLKIT.getScreenSize();
width = (int)(screenSize.width * widthPercent);
height = (int)(screenSize.height * heightPercent);
size = Math.min(width,
height);
area = new Dimension(size,
size);
return (area);
}
}
矩形类:
package com.comp2526.assign2c.a.a00892238;
import java.awt.Color;
import java.awt.Graphics2D;
public class Rectangle extends Shape {
// Initialize variables
private int x1; // x coordinate of first endpoint
private int y1; // y coordinate of first endpoint
private int x2; // x coordinate of second endpoint
private int y2; // y coordinate of second endpoint
private Color colour; // colour of the shape
// A no-parameter constructor that sets all the coordinates of the shape to
// 0 and the
// colour to Color.BLACK
public Rectangle() {
x1 = 0;
y1 = 0;
x2 = 0;
y2 = 0;
colour = Color.BLACK;
}
// A constructor that initializes the coordinates and colour to the values
// of the
// parameters supplied.
public Rectangle(int x1, int y1, int x2, int y2, Color col) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
this.colour = col;
}
public void setX1(int x1) {
this.x1 = x1;
}
public void setY1(int y1) {
this.y1 = y1;
}
public void setX2(int x2) {
this.x2 = x2;
}
public void setY2(int y2) {
this.y2 = y2;
}
public void setColor(Color colour) {
this.colour = colour;
}
public int getX1() {
return this.x1;
}
public int getY1() {
return this.y1;
}
public int getX2() {
return this.x2;
}
public int getY2() {
return this.y2;
}
public Color getColor() {
return this.colour;
}
public int getWidth() {
return (Math.abs(x2 - x1));
}
public int getHeight() {
return (Math.abs(y2 - y1));
}
public int getUpperLeftX() {
return (Math.min(x1, x2));
}
public int getUpperLeftY() {
return (Math.min(y1, y2));
}
}
点类:
package com.comp2526.assign2c.a.a00892238;
public class Point {
private int x = 0;
private int y = 0;
public Point() {}
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
椭圆课:
package com.comp2526.assign2c.a.a00892238;
import java.awt.Color;
import java.awt.Graphics2D;
public class Oval {
// Initialize variables
private int x1; // x coordinate of first endpoint
private int y1; // y coordinate of first endpoint
private int x2; // x coordinate of second endpoint
private int y2; // y coordinate of second endpoint
private Color colour; // colour of the shape
// A no-parameter constructor that sets all the coordinates of the shape to
// 0 and the
// colour to Color.BLACK
public Oval() {
x1 = 0;
y1 = 0;
x2 = 0;
y2 = 0;
colour = Color.BLACK;
}
// A constructor that initializes the coordinates and colour to the values
// of the
// parameters supplied.
public Oval(int x1, int y1, int x2, int y2, Color col) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
this.colour = col;
}
public void setX1(int x1) {
this.x1 = x1;
}
public void setY1(int y1) {
this.y1 = y1;
}
public void setX2(int x2) {
this.x2 = x2;
}
public void setY2(int y2) {
this.y2 = y2;
}
public void setColor(Color colour) {
this.colour = colour;
}
public int getX1() {
return this.x1;
}
public int getY1() {
return this.y1;
}
public int getX2() {
return this.x2;
}
public int getY2() {
return this.y2;
}
public Color getColor() {
return this.colour;
}
public int getWidth() {
return (Math.abs(x2 - x1));
}
public int getHeight() {
return (Math.abs(y2 - y1));
}
public int getUpperLeftX() {
return (Math.min(x1, x2));
}
public int getUpperLeftY() {
return (Math.min(y1, y2));
}
}
答案 0 :(得分:0)
在你的ShapeFrame类中,如果你像这样制作savebtn()方法,那么你的File-&gt; Save选项会将图像保存在你从保存对话框中选择的位置,其他按钮和你必须这样做但你的文件 - &gt;保存选项将使用此
保存文件public static void savebtn(DrawPad dp) {
DrawPad dp1 = dp;
//String sb = "gg";
/*
public void save() throws IOException{
ImageIO.write(paintImage, "PNG", new File("filename.png"));
}*/
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new File("/home/me/Documents"));
int retrieval = chooser.showSaveDialog(null);
if (retrieval == JFileChooser.APPROVE_OPTION) {
try {
//FileWriter fw = new FileWriter(chooser.getSelectedFile()+".png");
//fw.write(sb.toString());
//fw.close();
File f = chooser.getSelectedFile();
String filePath = f.getPath();
if(!filePath.toLowerCase().endsWith(".png"))
{
f = new File(filePath + ".png");
}
ImageIO.write((RenderedImage) dp1.image, "PNG", f);
//ImageIo.
} catch (Exception ex) {
ex.printStackTrace();
}
}
}