我正在尝试使用java GUI组件使游戏像精简版一样。我被困在这里,当一个动作发生时我怎么能得到我的按钮的背景颜色?在JAVA API中有像JButton.getBackground()
这样的方法。
在我的程序中,当我点击按钮我想要点击按钮的背景颜色,我想在特定位置绘制该颜色的椭圆。
这是我的代码
/**
* Action Listener for Buttons
*/
class ButtonAction implements ActionListener {
public void actionPerformed(ActionEvent e) {
setColor(getBackground()); // here i want to get background color as light blue.
}
}
b1 = new JButton("o");
Color c1 = new Color(100,255,255);// this is light blue color
b1.setBackground(c1);
ActionListener listener = new ButtonAction();
b1.addActionListener(listener);
/**
* this method will set vakue of the color and that color will use to draw oval
* filled with that color.
*/
public void setColor(Color C) {
this.c = C;
}
您需要通过在ActionListener的ActionEvent参数上调用.getSource()
来按下按钮:
class ButtonAction implements ActionListener {
public void actionPerformed(ActionEvent e) {
// get the button that was pressed
AbstractButton button = (AbstractButton) e.getSource();
// get its background Color
Color color = button.getBackground();
// TODO: do what you want with the color
}
}
setColor(getBackground());
中的getBackground指的是this.getBackground()
,它是您实现代码的类。这是一个JFrame或其他具有getBackground的对象,但不是你的Button b1。
您想获取事件源组件(即单击的JButton)并获取其背景颜色(((JComponent)e.getSource()).getBackground()
)。