如何在Java中将一个Swing组件的Graphics图像复制到另一个 [英] How to copy Graphics Image of one Swing Component to another in Java
问题描述
我刚刚在3个月前开始了我的 Java
编程,这里是我的问题 -
将 JLabel
或 JPanel
图形复制到另一个 JLabel
或 JPanel
。
我已经使用过 -
<! - Source JLabel srcLabel - >
JLabel dest = new JLabel();
dest.paint(srcLabel.getGraphics());
panel.add(dest);
dest.validate();
但由于缺乏知识,请帮助。
首先查看在AWT和Swing中绘制 永远不要使用
和
getGraphics
一般来说,您应该避免调用 paint
,而是使用 print
或 printAll
。这将禁用正常绘画过程中固有的双缓冲,它可以发出
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));
假设已经显示 srcLabel
并布置。
现在问题是为什么?简单地设置第二个标签的文本
和图标
属性并不容易,因此它与第一个标签匹配?
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?
这篇关于如何在Java中将一个Swing组件的Graphics图像复制到另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!