The reason this will not work is because pack() not called (to set all width and height values) until the panel is triggered, so the height and width are not set yet. And BufferedImage throws an exception if the width or height are non-positive integers.
So why don't you just set the values โโyourself? Here's how to do it in your example:
private void initPanel() { final int width = 600; final int height = 600; this.setPreferredSize(new Dimension(width, height)); junction = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR); graphics = junction.createGraphics(); setBackground(Color.white); }
Alternatively: If you have a requirement that the image should be resized using the component, you need to do this. I am sure that when pack() is called, it fires the ComponentListener.componentResized() event, so this should work when you trigger the component, even if you don't resize the component. So instead, do it in your code:
private void initPanel() { this.setPreferredSize(new Dimension(600, 600)); this.addComponentListener(new ComponentListener() { public void componentResized(ComponentEvent e) { Component c = (Component) e.getSource(); Dimension d = c.getSize(); resizeImage(d); } }); this.setBackground(Color.white); } public void resizeImage(Dimension d) { junction = new BufferedImage(d.getWidth(), d.getHeight(), BufferedImage.TYPE_3BYTE_BGR); graphics = junction.createGraphics(); }
source share