Java event handler String error

246 views Asked by At

I am trying to make a GUI application where I am using 2-D array registered with an ActionListener. At compile time I am getting a String s = ((Button)o).getLabel(); declaration not valid here. error. In my application if you click the button every "x" label on button should toggle to "o". The code I used is:

from constructor

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");

    }
1

There are 1 answers

4
Kevin DiTraglia On BEST ANSWER

You can't declare a new String within an if statement without brackets.

You'd have to write:

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

Which doesn't really make sense since the string goes out of scope immediately. What you probably want is something like this:

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