【发布时间】:2011-11-20 22:36:46
【问题描述】:
我正在为班级制作一款游戏,对于这个游戏,我有一组 JButton,它们需要能够根据某些因素改变颜色。我已经解决了这一切,并且正在使用 setBackground(Color) 更改颜色,但现在我正在尝试更改按钮的形状并且仍然能够更改颜色。 我当前的代码是:
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
public class CircleButton extends JButton {
Graphics g = this.getGraphics();
public CircleButton(){
super();
setContentAreaFilled(false);
}
protected void paintComponent(Graphics g) {
g.setColor(Color.pink);
g.fillOval(0, 0, getSize().width-1, getSize().height-1);
super.paintComponent(g);
}
public void changeColor(Color c) {
g.setColor(Color.blue);
g.fillOval(0, 0, getSize().width-1, getSize().height-1);
super.paintComponent(g);
}
}
当我更改我的其他代码以使用它而不是 JButton 时,它可以工作,我从一个 8x8 的粉红色圆圈网格开始,这正是我想要的。但现在我无法改变颜色。我已经尝试添加上面显示的 changeColor 方法,但是当它到达第 20 行(g.setColor(Color.blue))时,我得到了一个 nullPointerException。 我认为问题在于我如何使用 Graphics,但我无法确定具体的解决方案。 有人有什么建议吗?
【问题讨论】:
-
noooo .... 你永远不会在 Swing 中使用 component.getGraphics!
标签: java swing colors jbutton shape