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

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

最佳答案

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

关于java - 如何使用单选按钮更改 GUI 中形状的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33799734/

相关文章:

java - Facebook 登录错误 "disabled Oauth client flow"但我已启用它

java - JAXB 解码删除换行符

android - 特定单选按钮 - 为第一个/最后一个按钮设置不同样式的最简单方法

java - 带循环的天文学助手 Java 菜单驱动程序

java - JPA/Hibernate ManyToMany 不可为空约束

java - 给定一串单词,在字典中查找所有单词

javascript - 没有标签的样式单选按钮

java - 是否可以让单选按钮彼此不相邻但仍可在同一个单选组中工作?

javascript - 使用 jQuery 捕获当前(不是之前)选择的单选按钮的值

jquery - 使用 btn-group 时,单选按钮值未正确发送