如何在Java中将一个Swing组件的Graphics图像复制到另一个 [英] How to copy Graphics Image of one Swing Component to another in Java

查看:126
本文介绍了如何在Java中将一个Swing组件的Graphics图像复制到另一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚在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

code>,这只是一个糟糕的主意,并且会导致您无法结束问题。



一般来说,您应该避免调用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆