java - 引用 JPanel Action 监听器内部的类

标签 java swing jframe jpanel this

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

我的 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。换句话说:这个 thisthis 的通常含义不同 - 它不引用“外部”MainPanel 对象,而是引用内部 ActionListener 对象!

您必须使用MainPanel.this来代替!

关于java - 引用 JPanel Action 监听器内部的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33088903/

相关文章:

java - 使用 jodatime 查找剩余日期和时间

java - JFrame : it shows a list of number instead of the image 的问题

java - 如何使用已从 Cotainer 放置 JLabel 的方法?

java - 无法在 java 匹配中加载属性-

java - 在 Spring [Boot] 中手动解决依赖关系

java - JPA2乐观锁

java - 制作一个可以从另一个类打印的文本区域

java - NoClassDefFoundError:无法初始化类 com.jidesoft.swing.JideSwingUtilities

java - swing 中的图标字体 : font icons not appear in JLabel

java - 将图像添加到 NetBeans 中的 JPanel