package GUI;
import javax.swing.JButton;
import javax.swing.JFrame;
import java.awt.Container;
import java.awt.FlowLayout;import java.awt.*;public class ShowFlowLayout extends JFrame{
public ShowFlowLayout(){
//Get the content pane of the frame
Container container=getContentPane();
Checkbox jck;
CheckboxGroup g1;

container.setLayout(new FlowLayout(FlowLayout.LEFT,10,20));

//Add buttons to the frame
for(int i=0;i<10;i++)
container.add(new JButton("Component "+i));
JButton jbtOK=new JButton("OK");
container.add(jbtOK); g1=new CheckboxGroup();
jck=new Checkbox("click me!",g1,true);
container.add(jck);

jck.addItemListener(new ItemListener(){为什么在这一行有这样的错误ItemListener cannot be resolved to a type public void itemStateChanged(ItemEvent evt){
if(evt.getStateChange()==ItemEvent.SELECTED)
but1.setForeground(Color.red);
}
});
JButton but1=new JButton("Press me");
container.add(but1); } public static void main(String[] args) {
ShowFlowLayout frame=new ShowFlowLayout();
frame.setTitle("ShowFlowLayout");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 200);
frame.setVisible(true);
}}

解决方案 »

  1.   

    没导包。ItemListener在java.at.event包里面
      

  2.   

    导入包以后   在它下面  but1又不能被识别了
      

  3.   

    注意到匿名类的使用,它不能访问本地变量,只能访问常量,而且你的but1明显是先使用而后定义,应该把它放到前面去.
    package GUI;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import java.awt.Container;
    import java.awt.FlowLayout;import java.awt.*;
    import java.awt.event.ItemEvent;
    import java.awt.event.ItemListener;public class A extends JFrame{
    public A(){
    //Get the content pane of the frame
    Container container=getContentPane();
    Checkbox jck;
    CheckboxGroup g1;container.setLayout(new FlowLayout(FlowLayout.LEFT,10,20));//Add buttons to the frame
    for(int i=0;i<10;i++)
    container.add(new JButton("Component "+i));
    JButton jbtOK=new JButton("OK");
    container.add(jbtOK);g1=new CheckboxGroup();
    jck=new Checkbox("click me!",g1,true);
    container.add(jck);
    final JButton but1=new JButton("Press me");
    jck.addItemListener(new ItemListener(){    public void itemStateChanged(ItemEvent evt) {
    if(evt.getStateChange()==ItemEvent.SELECTED)
       but1.setForeground(Color.red);

    }
    });container.add(but1);}public static void main(String[] args) {
    A frame=new A();
    frame.setTitle("ShowFlowLayout");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(200, 200);
    frame.setVisible(true);
    }}