Reputation: 6404
What I'm trying to do is to get an already buffered image painted to a JFrame.
JFrame p1=new JFrame();
p1.getContentPane();
p1.setSize(new Dimension(h,w));
p1.setVisible(true);
p1.update(bufferedImage.getGraphics());
This is the code so far. bufferedImage is a buffered image, but this code only opens the JFrame and doesn't paint the image. I've never worked with graphics before. Thanks
Upvotes: 0
Views: 1590
Reputation: 25184
See this working code :
public static void main(String[] args) throws Exception {
BufferedImage buf=null;
try {
buf = ImageIO.read(new File("estbest.jpg"));
} catch (Exception e) {
System.out.println(e.getMessage());
}
new ImageFrame(buf, "Input Image ");
}
ImageFrame Class :
public class ImageFrame extends JFrame {
BufferedImage image;
public ImageFrame(final BufferedImage image) {
this(image, "No Title");
}
public ImageFrame(final BufferedImage image, final String title) {
this.image = image;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if (image != null) {
setSize(image.getWidth(null), image.getHeight(null));
} else {
setSize(250, 90);
}
setTitle(title);
setVisible(true);
repaint();
}
});
}
public void paint(Graphics g) {
if (image == null) {
g.setColor(Color.BLACK);
g.fillRect(0, 0, 250, 90);
System.out.println("image null");
g.setFont(new Font("Arial", Font.BOLD, 24));
g.setColor(Color.RED);
g.drawString("Invalid or No Image", 10, 50);
} else {
g.drawImage(image, 0, 0, null);
}
}
}
Source : Java: Loading images in JFrame - Reusable ImageFrame
Upvotes: 1
Reputation: 109823
1) put BufferedImage as Icon to the JLabel
2) don't paint directly to the JFrame
put there JComponent / JPanel
Upvotes: 2