2015-10-12 15 views
0

我正在嘗試在動作偵聽器中的方法中引用我的類,因此我可以通過該方法傳遞它。我的代碼看起來有點像這樣:請參閱JPanel動作列表器中的類

我的mainPanel類:

public class MainPanel extends JPanel{  

private JButton submitButton; 
JTextArea consoleOutput; 

public MainPanel(){ 

    Border border = BorderFactory.createLineBorder(Color.LIGHT_GRAY); 
    setLayout(null); 
    setBackground(Color.WHITE); 
    Font f1 = new Font("Arial", Font.PLAIN, 14); 

    submitButton = new JButton("Get Cards"); 
    submitButton.setBounds(35, 285, 107, 49); 
    submitButton.setFont(f1); 

    consoleOutput = new JTextArea(); 
    consoleOutput.setBounds(199, 122, 375 , 210); 
    consoleOutput.setBorder(BorderFactory.createCompoundBorder(border, BorderFactory.createEmptyBorder(3, 4, 0, 0))); 
    consoleOutput.setEditable(false); 
    consoleOutput.setFont(f1); 

    submitButton.addActionListener(new ActionListener(){ 
     public void actionPerformed(ActionEvent e){ 
      String username; 
      String password; 
      Cards cards = new Cards(); 
      cards.openTabs(username, password, this); //THIS IS THE METHOD IM TRYING TO PASS THE CLASS INTO 
      } 

     }); 
     add(submitButton); 
     add(consoleOutput); 
    } 
} 

我的卡片類:

public class Cards{ 

    public void openTabs(String username, String password, MainPanel panel){ 
     panel.consoleOutput.setText(username + ", " + password); 
    } 

在日食它強調在我的mainPanel的方法,這就是問題所在或錯誤是:

The method openTabs(String, String, MainPanel) in the type Cards is not applicable for the arguments (String, String, new ActionListener(){}) 

我該怎麼辦?我應該通過什麼,而不是因爲它似乎沒有工作。我迷路了,不知道該怎麼辦,任何幫助表示讚賞!

+1

關於代碼質量的注意事項:顯然你只是學習用Java編程,但它可能對你有好處,也學習如何編寫不僅有效的代碼,而且還有「好」的代碼。因此,我建議您查閱Robert Martin的「Clean Code」。 – GhostCat

回答

2

你的問題是,你正在使用匿名類中。換句話說:這個this不具有this的通常含義 - 它不會引用「外部」MainPanel對象,而是引用內部ActionListener對象!

您必須改用MainPanel.this

+0

非常感謝你 –

+0

不客氣,並且當這個行爲變得可用時,不要忘記「接受」我的回答;-) – GhostCat