0

我正在尝试编写一个程序,在屏幕上绘制一个圆圈,然后为您提供 3 个按钮(红色、黄色和绿色),然后单击该按钮相应地更改圆圈的填充颜色。

我想我已经接近了,我只是不知道如何实际创建一个绘制圆圈并改变颜色的方法。我可以编写一个方法来绘制和填充一个圆圈我只是在将它与 jbutton 合并时遇到问题

这是我到目前为止所拥有的:

(忽略未使用的导入)


采取了不同的方法,我不知道它是否更好。我的按钮显示,一切都只是在改变颜色时遇到问题。实际上现在我什至不能显示一个圆圈。我知道我需要调用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();           
    }
      });

   }
}
4

1 回答 1

1
  1. 用圆的当前颜色引入一个类变量/属性/...。
  2. 在您的事件处理程序中设置此变量
  3. 也调用“repaint();” 在您的事件处理程序中
  4. 覆盖该paintComponent()方法并使其以颜色绘制一个圆圈,您可以从类变量中读取该圆圈。

paintComponent(Graphics g)可能看起来像这样:

@Override
void paintComponent(Graphics g)
{
  g.setColor(currentColor);
  g.drawOval(50,50,100,100);
}
于 2012-11-01T00:56:52.863 回答