在JButton上绘制图形 [英] Drawing graphics on top of a JButton
问题描述
我有一种情况,在GridLayout上有一堆JButton。我需要每个JButton都有:
- 一个背景图片(但是如果需要,仍然保留默认按钮的样子) li>
- 由其他类顶部绘制的自定义图形
我对背景图像没有任何问题,因为我正在使用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()并不会帮助,因为我需要每个按钮都具有不同的图形。 解析方案
可以继承JButton并覆盖paintComponent()。
您可以通过为子类提供外部画家来处理每个具有不同图形的按钮。
public class MyButton扩展了JButton {
私人画家画家;
public void paintComponent(Graphics g){
super.paintComponent(g);
painter.paint(g);
public interface Painter {
public void paint(Graphics g);
}
你不能随意绘制按钮,因为绘画会得到当按钮下次重新粉刷时丢失。
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.
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.
public class MyButton extends JButton {
private Painter painter;
public void paintComponent(Graphics g) {
super.paintComponent(g);
painter.paint(g);
}
}
public interface Painter {
public void paint(Graphics g);
}
you cannot just paint on the button as you are doing as the painting will get lost when the button is next repainted.
这篇关于在JButton上绘制图形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!