如何使用单选按钮更改GUI中形状的颜色

时间:2015-11-19 09:22:55

标签: java radio-button

我正在尝试制作用于更改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 );
 }
}

1 个答案:

答案 0 :(得分:0)

您的RadioButtonHandler上的Hello在末尾添加一个repaint(),以便在按下单选按钮时重新绘制gui。