import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class textDemo extends JFrame{public textDemo(String title){
super(title);Container c=getContentPane();
c.setLayout(new FlowLayout());
JRadioButton rad1=new JRadioButton("我");
c.add(rad1);
JRadioButton rad2=new JRadioButton("你");
c.add(rad2);
JButton jb=new JButton("统计下");jb.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e){
JRadioButton rad1=new JRadioButton("我");
if(rad1.isSelected()){
rad1.setText("hello");
}
}
});c.add(jb);
setSize(300,250);
setVisible(true);
}
public static void main(String args[])
{
   textDemo td=new textDemo("测试下");}
}为什么点击按钮文本却没有改变呢?,给个答案吧

解决方案 »

  1.   

    1 在内部匿名类,你不能再构造一次了,应该使用父类的。
    2 内部类只能使用父类的类一级变量或者final的局部变量
    package test.swing;import java.awt.Container;
    import java.awt.FlowLayout;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JRadioButton;class TextDemo extends JFrame {  public TextDemo(String title) {
        super(title);
        Container c = getContentPane();
        c.setLayout(new FlowLayout());
        final JRadioButton  rad1 = new JRadioButton("我");
        c.add(rad1);
        JRadioButton rad2 = new JRadioButton("你");
        c.add(rad2);
        JButton jb = new JButton("统计下");
        jb.addMouseListener(new MouseAdapter() {
          public void mouseClicked(MouseEvent e) {
            System.out.println("1");
            // JRadioButton rad1 = new JRadioButton("我");
            if (rad1.isSelected()) {
              rad1.setText("hello");
            }
          }
        });
        c.add(jb);
        setSize(300, 250);
        setVisible(true);
      }  public static void main(String args[]) {
        TextDemo td = new TextDemo("测试下");
      }
    }