gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 13:12:52 25 4
gpt4 key购买 nike

我正在尝试制作单选按钮来更改 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com