2015-11-15 18 views
1

请告诉我错我的代码?当我想通过radioButton更改颜色时,它不会改变颜色。 if语句我已经把对我来说很有意义,但他们没有登记的背景变色的方法的setBackground。颜色不会改变通过我的if语句

import java.awt.BorderLayout; 
import java.awt.Color; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import javax.swing.ButtonGroup; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JPanel; 
import javax.swing.JRadioButton; 
import javax.swing.event.ChangeListener; 


public class GetTheColors extends JFrame 
{ 
private static final int FRAME_WIDTH = 300; 
private static final int FRAME_HEIGTH = 400; 

JLabel label; 
JPanel colorPanel; 
JFrame frame; 
JRadioButton redButton; 
JRadioButton blueButton; 
JRadioButton greenButton; 
ActionListener listen; 

public GetTheColors() 
     { 
      colorPanel = new JPanel(); 
      add(colorPanel, BorderLayout.CENTER); 

      RadioButtons(); 
      setColor(); 

      setSize(FRAME_WIDTH,FRAME_HEIGTH); 


     } 
class ChoiceListener implements ActionListener 
{ 
    public void actionPerformed(ActionEvent event) 
    { 
     setColor(); 
    } 
} 

public JPanel RadioButtons() 
{ 
    redButton = new JRadioButton("red"); 
    redButton.addActionListener(listen); 
    redButton.setSelected(true); 

    greenButton = new JRadioButton("green"); 
    greenButton.addActionListener(listen); 


    blueButton = new JRadioButton("blue"); 
    blueButton.addActionListener(listen); 


    ButtonGroup group = new ButtonGroup(); 
    group.add(redButton); 
    group.add(greenButton); 
    group.add(blueButton); 



    JPanel buttonPanel = new JPanel(); 
    buttonPanel.add(redButton); 
    buttonPanel.add(greenButton); 
    buttonPanel.add(blueButton); 


    add(buttonPanel, BorderLayout.NORTH); 
    return buttonPanel; 
} 
/** 
* 
*/ 
public void setColor() 
{ 
    if (redButton.isSelected()) 
    { 
     colorPanel.setBackground(Color.red); 
     colorPanel.repaint(); 
    } 
    else if (blueButton.isSelected()) 
    { 
     colorPanel.setBackground(Color.blue); 
     colorPanel.repaint(); 
    } 
    else if (greenButton.isSelected()) 
    { 
     colorPanel.setBackground(Color.green); 
     colorPanel.repaint(); 
    } 

} 

}

+0

试着用'的ActionListener听=新ChoiceListener()'。 – Tunaki

回答

0

您需要初始化的ActionListener:

ActionListener listen = new ChoiceListener(); 
+0

噢,那很简单,我一定是忘了这一点。我不知道我是如何错过的,谢谢你现在的作品。 –

+0

不客气。 –