我已设法保存图像,但无法从所选文件中加载图像,然后将其显示在我的图形面板上。我还希望它提示用户先保存当前文件,但我不确定如何解决这个问题。
我有三个课程如下:
驱动程序类
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
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.UIManager;
public class guiDriver {
private GUIPanel panel;
JFileChooser fileFinder;
JFrame frame;
JMenuBar menuBar;
JMenu fileMenu, helpMenu;
JMenuItem item1, item2, item3, item4, about;
JOptionPane optionPane = new JOptionPane("Are you sure you want to exit?", JOptionPane.QUESTION_MESSAGE,
JOptionPane.YES_NO_OPTION);
public static void main(String[] args) {
guiDriver app = new guiDriver();
}
public guiDriver() {
frame = new JFrame("Pen Simulator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new GUIPanel();
frame.add(panel);
// there is a method to set minimum size
frame.setMinimumSize(new Dimension(600, 400));
menuBar = new JMenuBar();
fileFinder = new JFileChooser();
// File Menu
fileMenu = new JMenu("File");
helpMenu = new JMenu("Help");
menuBar.add(fileMenu);
menuBar.add(helpMenu);
item1 = new JMenuItem("New");
item1.addActionListener(new itemListener());
item2 = new JMenuItem("Load");
item2.addActionListener(new itemListener());
item3 = new JMenuItem("Save");
item3.addActionListener(new itemListener());
item4 = new JMenuItem("Exit");
item4.addActionListener(new itemListener());
fileMenu.add(item1);
fileMenu.add(item2);
fileMenu.add(item3);
fileMenu.add(item4);
// Help Menu
about = new JMenuItem("About");
helpMenu.add(about);
frame.setJMenuBar(menuBar); // setting the Frames menubar as the newly
// created menubar
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
class itemListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
JMenuItem source = (JMenuItem) (e.getSource());
if (source.getText().equalsIgnoreCase("new")) {
panel.clearGraphics();
}
if (source.getText().equalsIgnoreCase("save")) {
BufferedImage img = panel.grabGraphics();
File f = new File("savedimage.jpg");
JFileChooser chooser = new JFileChooser();
chooser.setSelectedFile(f);
int rval = chooser.showSaveDialog(source);
if (rval == JFileChooser.APPROVE_OPTION) {
f = chooser.getSelectedFile();
try {
ImageIO.write(img, "JPEG", f);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// int returnVal = fileFinder.showSaveDialog(null);
}
if (source.getText().equalsIgnoreCase("load")) {
BufferedImage img2 = panel.grabGraphics();
JFileChooser chooser2 = new JFileChooser();
File fileLoad = new File(chooser2.getSelectedFile().getName());
chooser2.setSelectedFile(fileLoad);
int rval2 = chooser2.showOpenDialog(source);
if (rval2 == JFileChooser.APPROVE_OPTION) {
fileLoad = chooser2.getSelectedFile();
try {
img2 = ImageIO.read(fileLoad);
panel.setGraphics(img2);
} catch (IOException e1) {
e1.printStackTrace();
}
if (source.getText().equalsIgnoreCase("exit")) {
Object[] options = { "Yes", "No" };
int choice = JOptionPane.showOptionDialog(frame, "Are you sure you want to exit?",
"Graphics Application", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE,
UIManager.getIcon("OptionPane.errorIcon"), options, options[0]);
if (choice == JOptionPane.YES_OPTION) {
System.exit(0);
}
if (choice == JOptionPane.NO_OPTION) {
}
}
}
}
}
}
}
}
GUIPANEL
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class GUIPanel extends JPanel {
private JTextField userCommand;
private JLabel instruction1;
private JButton instruct, clear;
private GraphicsPanel graphics;
private int penX, penY, angle;
private int currentDirection = 0;
private boolean penIsUp = false;
private Color penColour;
public GUIPanel() {
graphics = new GraphicsPanel();
setLayout(new BorderLayout());
// SOUTH PANEL CONSTRUCTOR
JPanel command = new JPanel();
command.setLayout(new BoxLayout(command, BoxLayout.LINE_AXIS));
instruction1 = new JLabel("Enter Command:");
// BUTTO
instruct = new JButton("Execute");
instruct.addActionListener(new ButtonListener());
clear = new JButton("Clear Graphics");
// TEXT FIELD
userCommand = new JTextField(10);
command.add(instruction1);
command.add(Box.createRigidArea(new Dimension(4, 0)));
command.add(userCommand);
command.add(Box.createRigidArea(new Dimension(2, 0)));
command.add(instruct);
command.add(Box.createRigidArea(new Dimension(2, 0)));
command.add(clear);
add(command, BorderLayout.SOUTH);
add(graphics, BorderLayout.CENTER);
init();
}
public void init() {
penX = graphics.getWidth() / 2;
penY = graphics.getHeight() / 2;
}
public void moveForward() {
String command = userCommand.getText().toLowerCase();
int distance = Integer.parseInt(command.replace("forward ", ""));
userCommand.setText("");
if (penIsUp == false) {
if (currentDirection == 0) {
graphics.drawLine(penColour, penX, penY, penX, (penY - distance));
penY = penY - distance;
}
if (currentDirection == 1) {
graphics.drawLine(penColour, penX, penY, penX + distance, penY);
penX = penX + distance;
}
if (currentDirection == 2) {
graphics.drawLine(penColour, penX, penY, penX, (penY + distance));
penY = penY + distance;
}
if (currentDirection == 3) {
graphics.drawLine(penColour, penX, penY, penX - distance, penY);
penX = penX - distance;
}
graphics.repaint();
} else if (penIsUp == true) {
penY = penY - distance;
}
}
public void moveBackward() {
String command = userCommand.getText().toLowerCase();
int distance = Integer.parseInt(command.replace("backward ", ""));
userCommand.setText("");
if (penIsUp == false) {
graphics.drawLine(penColour, penX, penY, penX, (penY + distance));
graphics.repaint();
penY = penY + distance;
} else if (penIsUp == true) {
penX = penX + distance;
}
}
public void penUp() {
penIsUp = true;
userCommand.setText("");
}
public void penDown() {
penIsUp = false;
userCommand.setText("");
}
public void clearGraphics() {
graphics.clear();
graphics.repaint();
}
public void saveFile() {
graphics.saveFile();
}
public BufferedImage grabGraphics() {
return graphics.grabImage();
}
public void setGraphics(BufferedImage img2) {
graphics.grabImage();
graphics.repaint();
}
class ButtonListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
if (userCommand.getText().equalsIgnoreCase("something")) {
System.out.println("you typed something");
userCommand.setText("");
}
else if (userCommand.getText().equalsIgnoreCase("turnleft")) {
currentDirection = currentDirection - 1;
if (currentDirection == -1) {
currentDirection = 3;
}
userCommand.setText("");
}
else if (userCommand.getText().equalsIgnoreCase("turnright")) {
currentDirection = currentDirection + 1;
if (currentDirection == 4) {
currentDirection = 0;
}
userCommand.setText("");
}
else if (userCommand.getText().startsWith("forward ")) {
try {
moveForward();
} catch (NumberFormatException e1) {
System.out.println("Invalid command");
}
}
else if (userCommand.getText().startsWith("backward ")) {
try {
moveBackward();
}
catch (NumberFormatException e1) {
System.out.println("Invalid command");
}
}
else if (userCommand.getText().equalsIgnoreCase("black")) {
penColour = Color.BLACK;
userCommand.setText("");
}
else if (userCommand.getText().equalsIgnoreCase("green")) {
penColour = Color.GREEN;
userCommand.setText("");
}
else if (userCommand.getText().equalsIgnoreCase("red")) {
penColour = Color.RED;
userCommand.setText("");
}
else if (userCommand.getText().equalsIgnoreCase("reset")) {
graphics.clear();
penX = 0;
penY = 0;
userCommand.setText("");
graphics.repaint();
}
else if (userCommand.getText().equalsIgnoreCase("penUp")) {
penUp();
userCommand.setText("");
}
else if (userCommand.getText().equalsIgnoreCase("penDown")) {
penDown();
userCommand.setText("");
}
}
}
}
GraphicsPanel
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
@SuppressWarnings("serial")
public class GraphicsPanel extends JPanel {
/**
* The default BG colour of the image.
*/
private final static Color BACKGROUND_COL = Color.DARK_GRAY;
/**
* The underlying image used for drawing. This is required so any previous
* drawing activity is persistent on the panel.
*/
private BufferedImage image;
int w, h;
public GraphicsPanel() {
Dimension resolution = Toolkit.getDefaultToolkit().getScreenSize();
int width = (int) resolution.getWidth(); // casting the screen width to
// integer
int height = (int) resolution.getHeight(); // casting the scren height
// to integer
image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// Set max size of the panel, so that is matches the max size of the
// image.
setMaximumSize(new Dimension(image.getWidth(), image.getHeight()));
clear();
}
public BufferedImage grabImage() {
return image;
}
public void drawLine(Color color, int x1, int y1, int x2, int y2) {
Graphics g = image.getGraphics();
g.setColor(color);
g.translate(getWidth() / 2, getHeight() / 2);
g.drawLine(x1, y1, x2, y2);
}
/**
* Clears the image contents.
*/
public void clear() {
Graphics g = image.getGraphics();
g.setColor(BACKGROUND_COL);
g.fillRect(0, 0, image.getWidth(), image.getHeight());
}
@Override
public void paint(Graphics g) {
// render the image on the panel.
g.drawImage(image, 0, 0, null);
}
public void saveFile() {
try {
image = ImageIO.read(new File("Test.jpg"));
w = image.getWidth(null);
h = image.getHeight(null);
if (image.getType() != BufferedImage.TYPE_INT_RGB) {
BufferedImage image2 = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics big = image2.getGraphics();
big.drawImage(image, 0, 0, null);
}
} catch (IOException e) {
System.out.println("Invalid Image");
}
}
}
谢谢
答案 0 :(得分:2)
向GraphicsPanel添加方法,如下所示: -
public void setImage(BufferedImage image)
{
this.image = image
repaint();
}
并在装载区:
fileLoad = chooser2.getSelectedFile();
try
{
img2 = ImageIO.read(fileLoad);
panel.setImage(img2);
}
catch (IOException e1)
{
e1.printStackTrace();
}