Java 事件处理程序字符串错误



我正在尝试制作一个GUI应用程序,其中我正在使用通过ActionListener注册的2-D数组。在编译时,我收到一个String s = ((Button)o).getLabel(); declaration not valid here.错误。在我的应用程序中,如果您单击按钮,按钮上的每个"x"标签都应切换到"o"。我使用的代码是:

从构造函数

public ArrayDemo2()
{
    setLayout(new GridLayout(3,3));
    b= new Button[3][3];
    for(int i=0; i<b.length; i++)
    {
        for(int j=0; j<b[i].length; j++)
        {
            if(Math.random() < 0.5) add(b[i][j] = new Button("X"));
            else add(b[i][j] = new Button("O"));
            b[i][j].addActionListener(this);    
        }
    }
    addWindowListener(new WindowAdapter()
    {
        public void windowClosing(WindowEvent e)
        {
            System.exit(0);
        }
    });
    setSize(600,600);
    setVisible(true);
}
    public void actionPerformed(ActionEvent e)
    {
        Object o = e.getSource();
        String s = "";
        if(o instanceof Button)
        {
        s = ((Button)o).getLabel();
        }   
        if(s.equals("X"))
        ((Button)o).setLabel("O");
        else
        ((Button)o).setLabel("X");
    }

不能在没有括号的 if 语句中声明新的字符串。

你必须写:

if(o instanceof Button) {
    String s = ((Button)o).getLabel();
}

这实际上没有意义,因为字符串会立即超出范围。 你可能想要的是这样的东西:

String s = "";
if(o instanceof Button) {
    s = ((Button)o).getLabel();
}

相关内容

最新更新