2015-11-19 44 views
1

我正在嘗試製作改變GUI中形狀顏色的單選按鈕。到目前爲止,我已經設置了單選按鈕來工作,但顏色沒有改變。任何建議,這將是非常有益的。如何使用單選按鈕更改GUI中形狀的顏色

import javax.swing.*; 
import java.awt.*; 
import java.awt.event.*; 

public class Problem54 extends JFrame 
{ 
private Container contents; 
private JRadioButton red, orange, blue; 
private ButtonGroup colorGroup; 
private Color selectedColor = Color.RED; 

public Problem54() 
{ 
    super("Change the Color of a Circle"); 
    contents = getContentPane(); 
    contents.setLayout(new FlowLayout()); 

    red = new JRadioButton("red"); 
    orange = new JRadioButton("orange", true); 
    blue = new JRadioButton("blue"); 

    contents.add(red); 
    contents.add(orange); 
    contents.add(blue); 


    // create button group 
    colorGroup = new ButtonGroup(); 
    colorGroup.add(red); 
    colorGroup.add(orange); 
    colorGroup.add(blue); 

    // create RadioButtonHandler event handler 
    // and register it on the radio buttons 
    RadioButtonHandler roh = new RadioButtonHandler(); 
    red.addItemListener(roh); 
    orange.addItemListener(roh); 
    blue.addItemListener(roh); 

    setSize(250, 200); 
    setLocation(250,250); 
    setVisible(true); 
} 

public void paint(Graphics g) // required 
    { 
     super.paint(g); 

     int Diameter = 50; 
     int x_str =100, y_r1= 100, y_r2= 130; 
     int space = 5; 

     //Ring 1 
     g.setColor(selectedColor); 
     g.fillOval(x_str, y_r1, Diameter, Diameter); 

    } 

private class RadioButtonHandler implements ItemListener 
{ 
    public void itemStateChanged(ItemEvent ie) 
    { 
     if (ie.getSource() == red) 
      selectedColor = Color.RED; 
     else if (ie.getSource() == orange) 
      selectedColor = Color.ORANGE; 
     else if (ie.getSource() == blue) 
      selectedColor = Color.BLUE; 

     shapes.add(new ShapeItem(new Rectangle2D.Double(110, 1, 100, 100), 
       DEFAULT_COLOR)); 
    } 
} 


public static void main(String [] args) 
{ 
    Problem54 cc = new Problem54(); 
    cc.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
} 
} 

回答

0

您好您RadioButtonHandler在末尾添加一個重繪(),以便當按下單選按鈕的GUI被粉刷一新。