New to Java - Need to display an image in a window using JAVA
I am new to JAVA and have a project that manipulates images. I am able to save the new image to a file but want to display it in a window on the screen. Here is the code I am using. The window opens but the image doesn't display. Resultsimage is a BuffereImage that contains the new image.
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final test t = new test();
f.add(t,BorderLayout.CENTER);
JButton b = new JButton("Save Image");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
BufferedImage bi = new BufferedImage(
t.getWidth(),t.getHeight(),
BufferedImage.TYPE_INT_RGB);
Graphics2D g = bi.createGraphics();
t.paintComponent(g);
try {
ImageIO.write(bi,"JPEG",
new File("image.jpg"));
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
});
f.add(b,BorderLayout.SOUTH);
f.pack();
f.setVisible(true);
}
});
}
}
Ashok
JPanel panel = new JPanel(){
@Override
public void paintComponent(Graphics g) {
BufferedImage image = null; // get your buffered image.
Graphics2D graphics2d = (Graphics2D) g;
graphics2d.drawImage(image, 0, 0, null);
super.paintComponents(g);
}
};
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(resultsimage, 5, 5, resultsimage.getWidth(), resultsimage.getHeight(), Color.WHITE, null);
}
then make a call to above passing g
paintComponent(g);