-1

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
    As some answers have already shown. Braces solve the compiler issue. In general, always put single line if and while statement in braces. It visually groups the logic and makes easy to avoid adding another line of code and mistakenly thinking it is captured by the the condition. – eclipz905 Nov 21 '14 at 18:51
  • `if(o instanceof Button) { Button b = (Button) o; b.setLabel( b.getLabel().equals("X") ? "O" : "X" ); }` –  Nov 21 '14 at 20:59

1 Answers1

0

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();
}
Kevin DiTraglia
  • 25,746
  • 19
  • 92
  • 138