Placing an image in a component
Hi, I hope this is not a multipost...
Here is my problem, I have a Class that draws a graphic2d and saves it in a JPEG format, now, my problem is, I want it to be placed in a component, in a canvas or in a jpanel maybe, so i can preview the image before i save it to JPEG.
Thx in advance...
# 2
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;
public class ShowIt extends JPanel implements ActionListener {
public void actionPerformed(ActionEvent e) {
BufferedImage image = getImage();
if(isOkay(image))
saveImage(image);
}
private void saveImage(BufferedImage image) {
try {
File file = new File("showIt.jpg");
ImageIO.write(image, "jpg", file);
} catch(IOException e) {
System.out.println("Write error " + e.getMessage());
}
}
private boolean isOkay(BufferedImage image) {
ImageIcon icon = new ImageIcon(image);
int retVal = JOptionPane.showConfirmDialog(this, icon, "Okay to save?",
JOptionPane.YES_NO_OPTION);
return retVal == JOptionPane.YES_OPTION;
}
private BufferedImage getImage() {
int w = getWidth(), h = getHeight();
int type = BufferedImage.TYPE_INT_RGB;
BufferedImage image = new BufferedImage(w, h, type);
Graphics2D g2 = image.createGraphics();
paint(g2);
g2.dispose();
return image;
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
int w = getWidth();
int h = getHeight();
g2.setPaint(Color.blue);
g2.draw(new Rectangle2D.Double(w/16, h/16, w*7/8, h*7/8));
g2.setPaint(Color.green.darker());
g2.draw(new Line2D.Double(w/16, h/16, w*15/16, h*15/16));
}
private JPanel getLast() {
JButton button = new JButton("Save Image");
button.addActionListener(this);
JPanel panel = new JPanel();
panel.add(button);
return panel;
}
public static void main(String[] args) {
ShowIt test = new ShowIt();
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(test);
f.getContentPane().add(test.getLast(), "Last");
f.setSize(400,400);
f.setLocation(200,200);
f.setVisible(true);
}
}