我试图在操作监听器中的方法中引用我的类,以便我可以通过该方法传递它。我的代码看起来有点像这样:
我的 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);
}
在 Eclipse 中,它强调了我的 MainPanel 中的方法,这就是问题或错误:
The method openTabs(String, String, MainPanel) in the type Cards is not applicable for the arguments (String, String, new ActionListener(){})
我该怎么办?我应该传递什么而不是这个,因为它似乎不起作用。我迷路了,不知道该怎么办,非常感谢任何帮助!!
最佳答案
您的问题是您在匿名内部类中使用this。换句话说:这个 this
与 this
的通常含义不同 - 它不引用“外部”MainPanel 对象,而是引用内部 ActionListener 对象!
您必须使用MainPanel.this
来代替!
关于java - 引用 JPanel Action 监听器内部的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33088903/