2012-10-31 124 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的答案(就像我已經完成的那樣),因爲它非常有幫助 –