I just started my Java
programming 3 months before and here with my issue that is-
How to copy a JLabel
or JPanel
Graphics to another JLabel
or JPanel
.
I have used -
<!--Source JLabel srcLabel-->
JLabel dest = new JLabel();
dest.paint(srcLabel.getGraphics());
panel.add(dest);
dest.validate();
but due to lack of knowledge I stucked here. Please help.
Start by having a look at Painting in AWT and Swing
and Performing Custom Painting for more information about how painting works.
Never use getGraphics
, this is just a bad idea and will cause you no end of issues.
Generally speaking, you should avoid calling paint
directly, and instead use print
or printAll
. This will disable the double buffering inherent in the normal painting process which can issues
JLabel srcLabel = new JLabel();
JLabel dest = new JLabel();
BufferedImage img = new BufferedImage(srcLabel.getWidth(), srcLabel.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = img.createGraphics();
srcLabel.printAll(g2d);
g2d.dispose();
dest.setIcon(new ImageIcon(img));
This assumes that srcLabel
has already been displayed and laid out.
Now the question is why? Wouldn't be easier to simply set the text
and icon
properties of the second label so it matches the first?