参考 JPanel actionlistener 里面的 class

Refer to the class inside of a JPanel action listner

我试图在动作侦听器中的方法中引用我的 class,以便我可以通过该方法传递它。我的代码看起来有点像这样:

我的主面板Class:

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);
    }   
}

我的卡片Class:

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(){})   

我该怎么办?我应该传递什么而不是这个,因为它似乎不起作用。我迷路了,不知道该怎么做,感谢任何帮助!!

您的问题是您在匿名 inner class 中使用 this。换句话说:这个 this 没有 this 的通常含义 - 它不是指 "outer" MainPanel 对象,而是内部 ActionListener 对象!

您必须改用 MainPanel.this