如何“绘画”在 JPanel 上的 JLabels 上?
我有一组 JLabel
,每个 JLabel 都包含一个字母(通过 seText()),不透明,背景设置为白色,位于带有 GridLayout< 的
JPanel
上/code> 因此标签形成了一个表格。 我正在做一个简单的动画,突出显示某些行和列,然后显示交叉点。我可以使用标签的 setBackground()
来达到此目的,但我认为如果能够使用 Graphics
对象(也许绘制一个绕路口转一圈,然后清除它)。 我尝试扩展 JLabel
,或直接在 JPanel
上绘图(在方法中使用 getGraphics()
),但它不起作用,我在这种情况下,认为绘图位于标签后面。我不知道在这两种情况下“绘画”代码应该放在哪里,屏幕上什么也没有出现。
简而言之,像下面这样的方法可以用来在标签上绘图吗?
它应该是 JLabel 还是 JPanel 方法?
public void drawsomething() {
Graphics2D g2d = (Graphics2D) getGraphics();
g2d.fillRect(100, 100, 100, 100);
}
I have a set of JLabel
s, each containing a letter (via seText()), opaque and background set to white, on a JPanel
with a GridLayout
so the labels are forming a table.
I am doing a simple animation of highlighting certain rows and columns then there intersection. I can use the setBackground()
of labels for this purpose, but thought I'd have more "choices" if a was able to use a Graphics
object (maybe drawing a circle around intersection, then clearing it).
I tried to extend JLabel
, or drawing on the JPanel
directly(using getGraphics()
in a method) but it didn't work, I think the drawing is behind the labels in this case. I can't figure out where should the "painting" code be placed in either case, nothing appeared on the screen.
in short, a method like the following, can be used to draw on top of labels?
should it be a JLabel or a JPanel method?
public void drawsomething() {
Graphics2D g2d = (Graphics2D) getGraphics();
g2d.fillRect(100, 100, 100, 100);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您重写
paintChildren()
会怎样?What if you override
paintChildren()
?您可能想尝试使用 JLayeredPane 在现有 JComponent 之上绘制特定绘图,
请参阅此处的示例 http://docs.oracle.com/javase/tutorial/uiswing/components/layeredpane.html
You might want to try a JLayeredPane to paint your specific drawings on top of the existing JComponents
see example here http://docs.oracle.com/javase/tutorial/uiswing/components/layeredpane.html
我真的对绘图还不太了解,但只是创建了一个小示例代码供您查看,希望您能从中获得一些信息。为了在
JLabel上绘画,您可以使用它的paintComponent(Graphics g)
方法。示例代码:
I really don't know much about drawing stuff yet, but just created one small sample code for you to look at, hopefully you can get some information out of it. In order to paint on the
JLabel you can use it's paintComponent(Graphics g)
method.A Sample Code :
使用paintComponent(Graphics g) 而不是paint(Graphics g)。这将覆盖 GUI
Use paintComponent(Graphics g) instead of paint(Graphics g). That will paint over the GUI