Java This is part 2 of the question I asked earlier. It wasn\'t letting me post
ID: 3838477 • Letter: J
Question
Java
This is part 2 of the question I asked earlier. It wasn't letting me post it at once so I am posting it part of it here. Link is for the ealier question I asked and there is still part of this one that I haven't posted and I will do it in another question and provide the link. Thanks
https://www.chegg.com/homework-help/questions-and-answers/need-help-java-drawingpaneljava-fmlelementjava-fmlparserjava-fmlrendererjava-mainjava-file-q21909299
/**
The DrawingPanel class provides a simple interface for drawing persistent
images using a Graphics object. An internal BufferedImage object is used
to keep track of what has been drawn. A client of the class simply
constructs a DrawingPanel of a particular size and then draws on it with
the Graphics object, setting the background color if they so choose.
To ensure that the image is always displayed, a timer calls repaint at
regular intervals.
This version of DrawingPanel also saves animated GIFs, though this is kind
of hit-and-miss because animated GIFs are pretty sucky (256 color limit, large
file size, etc).
Recent features:
- save zoomed images (2011/10/25)
- window no longer moves when zoom changes (2011/10/25)
- grid lines (2011/10/11)
@author Marty Stepp
@version October 21, 2011
*/
import java.awt.AlphaComposite;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Composite;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.image.BufferedImage;
import java.awt.image.PixelGrabber;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.NoRouteToHostException;
import java.net.SocketException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.Vector;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JColorChooser;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSlider;
import javax.swing.KeyStroke;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.MouseInputListener;
import javax.swing.filechooser.FileFilter;
public final class DrawingPanel extends FileFilter
implements ActionListener, MouseMotionListener, Runnable, WindowListener {
// inner class to represent one frame of an animated GIF
private static class ImageFrame {
public Image image;
public int delay;
public ImageFrame(Image image, int delay) {
this.image = image;
this.delay = delay / 10; // strangely, gif stores delay as sec/100
}
}
// class constants
public static final String ANIMATED_PROPERTY = "drawingpanel.animated";
public static final String AUTO_ENABLE_ANIMATION_ON_SLEEP_PROPERTY = "drawingpanel.animateonsleep";
public static final String DIFF_PROPERTY = "drawingpanel.diff";
public static final String HEADLESS_PROPERTY = "drawingpanel.headless";
public static final String MULTIPLE_PROPERTY = "drawingpanel.multiple";
public static final String SAVE_PROPERTY = "drawingpanel.save";
public static final String ANIMATION_FILE_NAME = "_drawingpanel_animation_save.txt";
private static final String TITLE = "Drawing Panel";
private static final String COURSE_WEB_SITE = "http://www.cs.washington.edu/education/courses/cse142/12sp/drawingpanel.txt";
private static final Color GRID_LINE_COLOR = new Color(64, 64, 64, 128);
private static final int GRID_SIZE = 10; // 10px between grid lines
private static final int DELAY = 100; // delay between repaints in millis
private static final int MAX_FRAMES = 100; // max animation frames
private static final int MAX_SIZE = 10000; // max width/height
private static final boolean DEBUG = false;
private static final boolean SAVE_SCALED_IMAGES = true; // if true, when panel
// is zoomed, saves
// images at that zoom
// factor
private static int instances = 0;
private static Thread shutdownThread = null;
private static void checkAnimationSettings() {
try {
File settingsFile = new File(ANIMATION_FILE_NAME);
if (settingsFile.exists()) {
Scanner input = new Scanner(settingsFile);
String animationSaveFileName = input.nextLine();
input.close();
// *** TODO: delete the file
System.out.println("***");
System.out.println("*** DrawingPanel saving animated GIF: " + new File(animationSaveFileName).getName());
System.out.println("***");
settingsFile.delete();
System.setProperty(ANIMATED_PROPERTY, "1");
System.setProperty(SAVE_PROPERTY, animationSaveFileName);
}
} catch (Exception e) {
if (DEBUG) {
System.out.println("error checking animation settings: " + e);
}
}
}
private static boolean hasProperty(String name) {
try {
return System.getProperty(name) != null;
} catch (SecurityException e) {
if (DEBUG)
System.out.println("Security exception when trying to read " + name);
return false;
}
}
private static boolean propertyIsTrue(String name) {
try {
String prop = System.getProperty(name);
return prop != null
&& (prop.equalsIgnoreCase("true") || prop.equalsIgnoreCase("yes") || prop.equalsIgnoreCase("1"));
} catch (SecurityException e) {
if (DEBUG)
System.out.println("Security exception when trying to read " + name);
return false;
}
}
/*
* private static boolean propertyIsFalse(String name) { try { String prop =
* System.getProperty(name); return prop != null &&
* (prop.equalsIgnoreCase("false") || prop.equalsIgnoreCase("no") ||
* prop.equalsIgnoreCase("0")); } catch (SecurityException e) { if (DEBUG)
* System.out.println("Security exception when trying to read " + name);
* return false; } }
*/
// Returns whether the 'main' thread is still running.
private static boolean mainIsActive() {
ThreadGroup group = Thread.currentThread().getThreadGroup();
int activeCount = group.activeCount();
// look for the main thread in the current thread group
Thread[] threads = new Thread[activeCount];
group.enumerate(threads);
for (int i = 0; i < threads.length; i++) {
Thread thread = threads[i];
String name = ("" + thread.getName()).toLowerCase();
if (name.indexOf("main") >= 0 || name.indexOf("testrunner-assignmentrunner") >= 0) {
// found main thread!
// (TestRunnerApplet's main runner also counts as "main" thread)
return thread.isAlive();
}
}
// didn't find a running main thread; guess that main is done running
return false;
}
private static boolean usingDrJava() {
try {
return System.getProperty("drjava.debug.port") != null
|| System.getProperty("java.class.path").toLowerCase().indexOf("drjava") >= 0;
} catch (SecurityException e) {
// running as an applet, or something
return false;
}
}
private class ImagePanel extends JPanel {
private static final long serialVersionUID = 0;
private Image image;
public ImagePanel(Image image) {
setImage(image);
setBackground(Color.WHITE);
setPreferredSize(new Dimension(image.getWidth(this), image.getHeight(this)));
setAlignmentX(0.0f);
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
if (currentZoom != 1) {
g2.scale(currentZoom, currentZoom);
}
g2.drawImage(image, 0, 0, this);
// possibly draw grid lines for debugging
if (gridLines) {
g2.setPaint(GRID_LINE_COLOR);
for (int row = 1; row <= getHeight() / GRID_SIZE; row++) {
g2.drawLine(0, row * GRID_SIZE, getWidth(), row * GRID_SIZE);
}
for (int col = 1; col <= getWidth() / GRID_SIZE; col++) {
g2.drawLine(col * GRID_SIZE, 0, col * GRID_SIZE, getHeight());
}
}
}
public void setImage(Image image) {
this.image = image;
repaint();
}
}
// fields
private int width, height; // dimensions of window frame
private JFrame frame; // overall window frame
private JPanel panel; // overall drawing surface
private ImagePanel imagePanel; // real drawing surface
private BufferedImage image; // remembers drawing commands
private Graphics2D g2; // graphics context for painting
private JLabel statusBar; // status bar showing mouse position
private JFileChooser chooser; // file chooser to save files
private long createTime; // time at which DrawingPanel was constructed
private Timer timer; // animation timer
private ArrayList frames; // stores frames of animation to save
private Gif89Encoder encoder;
// private FileOutputStream stream;
private Color backgroundColor = Color.WHITE;
private String callingClassName; // name of class that constructed this panel
private boolean animated = false; // changes to true if sleep() is called
private boolean PRETTY = true; // true to anti-alias
private boolean gridLines = false;
private int instanceNumber;
private int currentZoom = 1;
private int initialPixel; // initial value in each pixel, for clear()
// construct a drawing panel of given width and height enclosed in a window
public DrawingPanel(int width, int height) {
if (width < 0 || width > MAX_SIZE || height < 0 || height > MAX_SIZE) {
throw new IllegalArgumentException("Illegal width/height: " + width + " x " + height);
}
checkAnimationSettings();
synchronized (getClass()) {
instances++;
instanceNumber = instances; // each DrawingPanel stores its own int number
if (shutdownThread == null && !usingDrJava()) {
shutdownThread = new Thread(new Runnable() {
// Runnable implementation; used for shutdown thread.
@Override
public void run() {
try {
while (true) {
// maybe shut down the program, if no more DrawingPanels are
// onscreen
// and main has finished executing
if ((instances == 0 || shouldSave()) && !mainIsActive()) {
try {
System.exit(0);
} catch (SecurityException sex) {
}
}
Thread.sleep(250);
}
} catch (Exception e) {
}
}
});
shutdownThread.setPriority(Thread.MIN_PRIORITY);
shutdownThread.start();
}
}
this.width = width;
this.height = height;
if (DEBUG)
System.out.println("w=" + width + ",h=" + height + ",anim=" + isAnimated() + ",graph=" + isGraphical() + ",save="
+ shouldSave());
if (isAnimated() && shouldSave()) {
// image must be no more than 256 colors
image = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_INDEXED);
// image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
PRETTY = false; // turn off anti-aliasing to save palette colors
// initially fill the entire frame with the background color,
// because it won't show through via transparency like with a full ARGB
// image
Graphics g = image.getGraphics();
g.setColor(backgroundColor);
g.fillRect(0, 0, width + 1, height + 1);
} else {
image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
}
initialPixel = image.getRGB(0, 0);
g2 = (Graphics2D) image.getGraphics();
g2.setColor(Color.BLACK);
if (PRETTY) {
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
}
if (isAnimated()) {
initializeAnimation();
}
if (isGraphical()) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
}
statusBar = new JLabel(" ");
statusBar.setBorder(BorderFactory.createLineBorder(Color.BLACK));
panel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
panel.setBackground(backgroundColor);
panel.setPreferredSize(new Dimension(width, height));
imagePanel = new ImagePanel(image);
imagePanel.setBackground(backgroundColor);
panel.add(imagePanel);
// listen to mouse movement
panel.addMouseMotionListener(this);
// main window frame
frame = new JFrame(TITLE);
// frame.setResizable(false);
frame.addWindowListener(this);
// JPanel center = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0));
JScrollPane center = new JScrollPane(panel);
// center.add(panel);
frame.getContentPane().add(center);
frame.getContentPane().add(statusBar, "South");
frame.setBackground(Color.DARK_GRAY);
// menu bar
setupMenuBar();
frame.pack();
center(frame);
frame.setVisible(true);
if (!shouldSave()) {
toFront(frame);
}
// repaint timer so that the screen will update
createTime = System.currentTimeMillis();
timer = new Timer(DELAY, this);
timer.start();
} else if (shouldSave()) {
// headless mode; just set a hook on shutdown to save the image
callingClassName = getCallingClassName();
try {
Runtime.getRuntime().addShutdownHook(new Thread(this));
} catch (Exception e) {
if (DEBUG)
System.out.println("unable to add shutdown hook: " + e);
}
}
}
// method of FileFilter interface
@Override
public boolean accept(File file) {
return file.isDirectory()
|| (file.getName().toLowerCase().endsWith(".png") || file.getName().toLowerCase().endsWith(".gif"));
}
// used for an internal timer that keeps repainting
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() instanceof Timer) {
// redraw the screen at regular intervals to catch all paint operations
panel.repaint();
if (shouldDiff() && System.currentTimeMillis() > createTime + 4 * DELAY) {
String expected = System.getProperty(DIFF_PROPERTY);
try {
String actual = saveToTempFile();
DiffImage diff = new DiffImage(expected, actual);
diff.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
} catch (IOException ioe) {
System.err.println("Error diffing image: " + ioe);
}
timer.stop();
} else if (shouldSave() && readyToClose()) {
// auto-save-and-close if desired
try {
if (isAnimated()) {
saveAnimated(System.getProperty(SAVE_PROPERTY));
} else {
save(System.getProperty(SAVE_PROPERTY));
}
} catch (IOException ioe) {
System.err.println("Error saving image: " + ioe);
}
exit();
}
} else if (e.getActionCommand().equals("Exit")) {
exit();
} else if (e.getActionCommand().equals("Compare to File...")) {
compareToFile();
} else if (e.getActionCommand().equals("Compare to Web File...")) {
new Thread(new Runnable() {
@Override
public void run() {
compareToURL();
}
}).start();
} else if (e.getActionCommand().equals("Save As...")) {
saveAs();
} else if (e.getActionCommand().equals("Save Animated GIF...")) {
saveAsAnimated();
} else if (e.getActionCommand().equals("Zoom In")) {
zoom(currentZoom + 1);
} else if (e.getActionCommand().equals("Zoom Out")) {
zoom(currentZoom - 1);
} else if (e.getActionCommand().equals("Zoom Normal (100%)")) {
zoom(1);
} else if (e.getActionCommand().equals("Grid Lines")) {
setGridLines(((JCheckBoxMenuItem) e.getSource()).isSelected());
} else if (e.getActionCommand().equals("About...")) {
JOptionPane.showMessageDialog(frame,
"DrawingPanel " + "Graphical library class to support Building Java Programs textbook "
+ "written by Marty Stepp and Stuart Reges " + "University of Washington "
+ "please visit our web site at: " + "http://www.buildingjavaprograms.com/",
"About DrawingPanel", JOptionPane.INFORMATION_MESSAGE);
}
}
public void addKeyListener(KeyListener listener) {
frame.addKeyListener(listener);
}
public void addMouseListener(MouseListener listener) {
panel.addMouseListener(listener);
}
public void addMouseListener(MouseMotionListener listener) {
panel.addMouseMotionListener(listener);
}
public void addMouseMotionListener(MouseMotionListener listener) {
panel.addMouseMotionListener(listener);
}
public void addMouseListener(MouseInputListener listener) {
panel.addMouseListener(listener);
panel.addMouseMotionListener(listener);
}
// erases all drawn shapes/lines/colors from the panel
public void clear() {
int[] pixels = new int[width * height];
for (int i = 0; i < pixels.length; i++) {
pixels[i] = initialPixel;
}
image.setRGB(0, 0, width, height, pixels, 0, 1);
}
// erases all drawn shapes/lines/colors from the panel
public void clearWithoutRepaint() {
Graphics g = image.getGraphics();
g.setColor(backgroundColor);
g.fillRect(0, 0, getWidth(), getHeight());
}
// method of FileFilter interface
@Override
public String getDescription() {
return "Image files (*.png; *.gif)";
}
// obtain the Graphics object to draw on the panel
public Graphics2D getGraphics() {
return g2;
}
// returns the drawing panel's width in pixels
public int getHeight() {
return height;
}
// returns the drawing panel's pixel size (width, height) as a Dimension
// object
public Dimension getSize() {
return new Dimension(width, height);
}
// returns the drawing panel's width in pixels
public int getWidth() {
return width;
}
// returns panel's current zoom factor
public int getZoom() {
return currentZoom;
}
// listens to mouse dragging
@Override
public void mouseDragged(MouseEvent e) {
}
// listens to mouse movement
@Override
public void mouseMoved(MouseEvent e) {
int x = e.getX() / currentZoom;
int y = e.getY() / currentZoom;
setStatusBarText("(" + x + ", " + y + ")");
}
// run on shutdown to save the image
@Override
public void run() {
if (DEBUG)
System.out.println("Running shutdown hook");
try {
String filename = System.getProperty(SAVE_PROPERTY);
if (filename == null) {
filename = callingClassName + ".png";
}
if (isAnimated()) {
saveAnimated(filename);
} else {
save(filename);
}
} catch (SecurityException e) {
} catch (IOException e) {
System.err.println("Error saving image: " + e);
}
}
// take the current contents of the panel and write them to a file
public void save(String filename) throws IOException {
BufferedImage image2 = getImage();
// if zoomed, scale image before saving it
if (SAVE_SCALED_IMAGES && currentZoom != 1) {
BufferedImage zoomedImage = new BufferedImage(width * currentZoom, height * currentZoom, image.getType());
Graphics2D g = (Graphics2D) zoomedImage.getGraphics();
g.setColor(Color.BLACK);
if (PRETTY) {
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
}
g.scale(currentZoom, currentZoom);
g.drawImage(image2, 0, 0, imagePanel);
image2 = zoomedImage;
}
// if saving multiple panels, append number
// (e.g. output_*.png becomes output_1.png, output_2.png, etc.)
if (isMultiple()) {
filename = filename.replaceAll("\*", String.valueOf(instanceNumber));
}
int lastDot = filename.lastIndexOf(".");
String extension = filename.substring(lastDot + 1);
// write file
// TODO: doesn't save background color I don't think
ImageIO.write(image2, extension, new File(filename));
}
// take the current contents of the panel and write them to a file
public void saveAnimated(String filename) throws IOException {
// add one more final frame
if (DEBUG)
System.out.println("saveAnimated(" + filename + ")");
frames.add(new ImageFrame(getImage(), 5000));
// encoder.continueEncoding(stream, getImage(), 5000);
// Gif89Encoder gifenc = new Gif89Encoder();
// add each frame of animation to the encoder
try {
for (int i = 0; i < frames.size(); i++) {
ImageFrame imageFrame = frames.get(i);
encoder.addFrame(imageFrame.image);
encoder.getFrameAt(i).setDelay(imageFrame.delay);
imageFrame.image.flush();
frames.set(i, null);
}
} catch (OutOfMemoryError e) {
System.out.println("Out of memory when saving");
}
// gifenc.setComments(annotation);
// gifenc.setUniformDelay((int) Math.round(100 / frames_per_second));
// gifenc.setUniformDelay(DELAY);
// encoder.setBackground(backgroundColor);
encoder.setLoopCount(0);
encoder.encode(new FileOutputStream(filename));
}
// set the background color of the drawing panel
public void setBackground(Color c) {
Color oldBackgroundColor = backgroundColor;
backgroundColor = c;
if (isGraphical()) {
panel.setBackground(c);
imagePanel.setBackground(c);
}
// with animated images, need to palette-swap the old bg color for the new
// because there's no notion of transparency in a palettized 8-bit image
if (isAnimated()) {
replaceColor(image, oldBackgroundColor, c);
}
}
// Enables or disables the drawing of grid lines on top of the image to help
// with debugging sizes and coordinates.
public void setGridLines(boolean gridLines) {
this.gridLines = gridLines;
imagePanel.repaint();
}
// sets the drawing panel's height in pixels to the given value
// After calling this method, the client must call getGraphics() again
// to get the new graphics context of the newly enlarged image buffer.
public void setHeight(int height) {
setSize(getWidth(), height);
}
// sets the drawing panel's pixel size (width, height) to the given values
// After calling this method, the client must call getGraphics() again
// to get the new graphics context of the newly enlarged image buffer.
public void setSize(int width, int height) {
// replace the image buffer for drawing
BufferedImage newImage = new BufferedImage(width, height, image.getType());
imagePanel.setImage(newImage);
newImage.getGraphics().drawImage(image, 0, 0, imagePanel);
this.width = width;
this.height = height;
image = newImage;
g2 = (Graphics2D) newImage.getGraphics();
g2.setColor(Color.BLACK);
if (PRETTY) {
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
}
zoom(currentZoom);
if (isGraphical()) {
frame.pack();
}
}
Explanation / Answer
Here is the java code for the above scenario:
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import javax.swing.*;
import javax.swing.event.*;
public class DrawingPanel implements ActionListener
{
public static final int DELAY = 250; private static final String DUMP_IMAGE_PROPERTY_NAME = "drawingpanel.save";
private static String TARGET_IMAGE_FILE_NAME = null;
private static final boolean PRETTY = true;
private static boolean DUMP_IMAGE = true;
private int width, height;
private JFrame frame;
private JPanel panel;
private BufferedImage image;
private Graphics2D g2;
private JLabel statusBar;
private long createTime;
static {
TARGET_IMAGE_FILE_NAME = System.getProperty(DUMP_IMAGE_PROPERTY_NAME);
DUMP_IMAGE = (TARGET_IMAGE_FILE_NAME != null);
}
public DrawingPanel(int width, int height) {
this.width = width;
this.height = height;
this.image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
this.statusBar = new JLabel(" ");
this.statusBar.setBorder(BorderFactory.createLineBorder(Color.BLACK));
this.panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0));
this.panel.setBackground(Color.WHITE);
this.panel.setPreferredSize(new Dimension(width, height));
this.panel.add(new JLabel(new ImageIcon(image)));
MouseInputAdapter listener = new MouseInputAdapter() {
public void mouseMoved(MouseEvent e) {
DrawingPanel.this.statusBar.setText("(" + e.getX() + ", " + e.getY() + ")");
}
public void mouseExited(MouseEvent e) {
DrawingPanel.this.statusBar.setText(" ");
}
};
this.panel.addMouseListener(listener);
this.panel.addMouseMotionListener(listener);
this.g2 = (Graphics2D)image.getGraphics();
this.g2.setColor(Color.BLACK);
if (PRETTY) {
this.g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
this.g2.setStroke(new BasicStroke(1.1f));
}
this.frame = new JFrame("CS305j Drawing Panel");
this.frame.setResizable(false);
this.frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
if (DUMP_IMAGE) {
DrawingPanel.this.save(TARGET_IMAGE_FILE_NAME);
}
System.exit(0);
}
});
this.frame.getContentPane().add(panel);
this.frame.getContentPane().add(statusBar, "South");
this.frame.pack();
this.frame.setVisible(true);
if (DUMP_IMAGE) {
createTime = System.currentTimeMillis();
this.frame.toBack();
} else {
this.toFront();
}
new Timer(DELAY, this).start();
}
public void actionPerformed(ActionEvent e) {
this.panel.repaint();
if (DUMP_IMAGE && System.currentTimeMillis() > createTime + 4 * DELAY) {
this.frame.setVisible(false);
this.frame.dispose();
this.save(TARGET_IMAGE_FILE_NAME);
System.exit(0);
}
}
public Graphics2D getGraphics() {
return this.g2;
}
public void setBackground(Color c) {
this.panel.setBackground(c);
}
public void setVisible(boolean visible) {
this.frame.setVisible(visible);
}
public void sleep(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {}
}
public void save(String filename) {
String extension = filename.substring(filename.lastIndexOf(".") + 1);
BufferedImage image2 = new BufferedImage(this.width, this.height, BufferedImage.TYPE_INT_RGB);
Graphics g = image2.getGraphics();
g.setColor(panel.getBackground());
g.fillRect(0, 0, this.width, this.height);
g.drawImage(this.image, 0, 0, panel);
try {
ImageIO.write(image2, extension, new java.io.File(filename));
} catch (java.io.IOException e) {
System.err.println("Unable to save image: " + e);
}
}
public void toFront() {
this.frame.toFront();
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.