在 JButton 上绘制图形
我遇到的情况是,GridLayout 上有一堆 JButton。我需要每个 JButton 都具有:
- 背景图像(但保留在需要时保持默认按钮外观的能力)
- 由其他类在顶部绘制的自定义图形
我对背景图像没有任何问题,因为我使用的是 setIcon()但我在背景上绘制东西时遇到问题。有一次我可以在按钮顶部绘图,但是单击按钮后,绘图就消失了。如何让按钮保持这种绘图状态?
基本上,我需要一种方法让我的 JButton 具有公共方法,允许另一个类在其上绘制任何内容,例如:
public void drawSomething() {
Graphics g = this.getGraphics();
g.drawOval(3,2,2,2);
repaint();
}
或者
public Graphics getGraphics() {
return this.getGraphics();
}
另一个类可以执行此操作:
button.getGraphics().drawSomething();
后者更符合我的要求,但第一个同样有用。
有什么办法可以解决这个问题吗?另外,重写父类方法 PaintComponent() 没有帮助,因为我需要每个按钮都有不同的图形。
I have a situation wherein I have a bunch of JButtons on a GridLayout. I need each of the JButtons to have:
- a background image (but retain the ability to keep the default button look if needed)
- custom graphics drawn on top by other classes
I have no trouble with the background image, since I am using setIcon() but I am having problems drawing things on top of the background. At one point I was able to draw on top of the button, but after the button was clicked, the drawings disappeared. How can make the button keep this drawing state?
Basically, I need a way for my JButtons to have public methods that would allow another class to draw anything on it such as:
public void drawSomething() {
Graphics g = this.getGraphics();
g.drawOval(3,2,2,2);
repaint();
}
or
public Graphics getGraphics() {
return this.getGraphics();
}
then another class could do this:
button.getGraphics().drawSomething();
The latter is more what I am looking for but the first is equally useful.
Is there any way to go about this? Also, overriding the parent class method paintComponent() doesn't help since I need each button to have different graphics.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以子类化 JButton 并重写 PaintComponent()。
您可以通过为子类提供外部“画家”来处理具有不同图形的每个按钮。或者只是为每个不同的图形设置不同的子类。
您不能像现在一样只在按钮上绘画,因为下次重新绘制按钮时绘画会丢失。
you can subclass JButton and override paintComponent().
you can handle each button having a different graphic by providing an external 'painter' to the subclass. Or just have a different subclass for each different graphic.
you cannot just paint on the button as you are doing as the painting will get lost when the button is next repainted.
您可以创建一个 BufferedImage 并在其上进行自定义绘制,然后在自定义 PaintComponent(...) 方法中绘制图像。
查看自定义绘画方法中的 DrawOnImage 示例。
You can create a BufferedImage and do custom painting on it and then draw the image in your custom paintComponent(...) method.
Look at the DrawOnImage example from Custom Painting Approaches.