简体   繁体   English

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

[英]How can I use radio buttons to change the color of a shape in a GUI

I am attempting to make radio buttons which change the color of a shape in a GUI. 我试图制作单选按钮以更改GUI中形状的颜色。 So far, I have the radio buttons set up to work, but the color isn't changing. 到目前为止,我已经设置了单选按钮,但是颜色没有改变。 Any advise on this would be extremely helpful. 关于此的任何建议将非常有帮助。

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 );
 }
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM