我正在嘗試製作一個GUI應用程序,其中使用了用ActionListener註冊的二維數組。在編譯時,我得到一個String s = ((Button)o).getLabel(); declaration not valid here.
錯誤。在我的應用程序中,如果您單擊按鈕,則按鈕上的每個「x」標籤都應切換到「o」。我使用的代碼是:Java事件處理程序字符串錯誤
從構造
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和while語句放在一起。它在視覺上對邏輯進行分組,並且很容易避免添加另一行代碼並錯誤地認爲它被條件捕獲。 – eclipz905 2014-11-21 18:51:17
'if(o instance of Button){b} =(Button)o; b.setLabel(b.getLabel()。equals(「X」)?「O」:「X」); }' – vaxquis 2014-11-21 20:59:31