How to copy Graphics Image of one Swing Component to another in Java

二次信任 提交于 2019-12-30 13:56:09

问题


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.


回答1:


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?



来源:https://stackoverflow.com/questions/35250385/how-to-copy-graphics-image-of-one-swing-component-to-another-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!