2014-11-21 56 views
-1

我正在嘗試製作一個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"); 

    } 
+1

由於一些答案已經顯示。大括號解決了編譯器問題。一般來說,總是把大括號中的單行if和while語句放在一起。它在視覺上對邏輯進行分組,並且很容易避免添加另一行代碼並錯誤地認爲它被條件捕獲。 – eclipz905 2014-11-21 18:51:17

+0

'if(o instance of Button){b} =(Button)o; b.setLabel(b.getLabel()。equals(「X」)?「O」:「X」); }' – vaxquis 2014-11-21 20:59:31

回答

0

你不能沒有括號的if語句中聲明瞭一個新的String。

你不得不寫:

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

這並沒有真正意義,因爲該字符串馬上超出範圍。你可能想要的是這樣的:

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

它不工作。它在註冊事件時顯示不兼容的類型 – 2014-11-21 18:41:28

+0

您發佈的代碼中沒有任何內容顯示任何事件註冊,所以我假設問題出現在您未在問題中發佈的代碼中。這應該解決你問到的'聲明在這裏無效'的錯誤消息。 – 2014-11-21 18:44:29

+0

請檢查我已編輯我的代碼。 – 2014-11-21 18:51:58