2012-10-31 46 views
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

您是否通过[摆动拉丝教程](http://docs.oracle.com/javase/tutorial/uiswing/painting/index不见了.html)呢?那就是我开始的地方,因为如果你不知道如何画一个圆圈,那你就死在水里。提示:你错过了最重要的方法,'paintComponent(...)'。 –

回答

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

paintComponent(Graphics g)可能是这个样子:

@Override 
void paintComponent(Graphics g) 
{ 
    g.setColor(currentColor); 
    g.drawOval(50,50,100,100); 
} 
+0

我的所有代码都没有在原始文章中复制,我为此道歉。我已经有“paintComponent”类...我仍然不确定如何使用“repaint()”方法。我需要传入参数吗?我是否在我的eventhandler类中重写“paintComponet()”? – user1789951

+0

我编辑原始帖子以包含我的“paintComponet”类 – user1789951

+0

@ user1789951:需要通过变量设置颜色,如Simon“says”(1+ to Simon),并不是像你所做的那样将它硬编码为'Color.blue',并且不,事件处理函数没有paintComopnent方法,只有派生自JComponent的类,比如JPanel,你应该投票给Simon的答案(就像我已经完成的那样),因为它非常有帮助 –