java绘图图形和事件处理
我试图写一个程序,在屏幕上画一个圆圈,然后给你3个按钮(红色、黄色和绿色),点击按钮相应地改变圆圈的填充颜色
我想我很接近了,我只是不知道如何创建一个方法来画圆和改变颜色。我可以写一个方法来画和填充一个圆,我只是在将它与jbutton合并时遇到了问题
这就是我到目前为止所做的:
(忽略未使用的导入)
采取了不同的方法,我不知道是否更好。我的按钮显示和一切只是有问题改变颜色。事实上,现在我甚至不能显示一个圆圈。我知道我需要在eventhandler中调用repaint();
,我只是不知道如何做。这是星期天,我花了这么多时间看视频和阅读示例,我就是不能让我的工作。我相信这很简单,但这让我很沮丧
public class test3 extends JPanel {
JRadioButton RED, YELLOW, GREEN;
Color currentColor;
public void paintComponent(Graphics g){
currentColor= Color.RED;
super.paintComponent(g);
this.setBackground(Color.WHITE);
g.setColor(currentColor);
g.fillOval(50, 50, 100, 100);
}
public static void main(String[] args) {
test3 frame = new test3();
frame.setSize(500,500);
frame.setVisible(true);
}
public test3 (){
JPanel jpRadioButtons=new JPanel();
jpRadioButtons.setLayout(new GridLayout(1,1));
jpRadioButtons.add(RED=new JRadioButton("RED"));
jpRadioButtons.add(GREEN=new JRadioButton("GREEN"));
jpRadioButtons.add(YELLOW=new JRadioButton("YELLOW"));
add(jpRadioButtons, BorderLayout.SOUTH);
ButtonGroup group=new ButtonGroup();
group.add(RED);
group.add(YELLOW);
group.add(GREEN);
GREEN.addActionListener(new ActionListener()
{
public void actionPerormed(ActionEvent e)
{
currentColor = Color.GREEN;
repaint();
}
});
}
}
# 1 楼答案
paintComponent()
方法,并使其在颜色中绘制一个圆,可以从类变量中读取李>你的
paintComponent(Graphics g)
可能看起来像这样: