【问题标题】:Can't use imported class in an anonymous class [closed]不能在匿名类中使用导入的类[关闭]
【发布时间】:2012-07-24 04:37:38
【问题描述】:

我正在从 Python 切换到 Java,但我的项目有点困难。我正在用 Swing 为我教的一些密码编写一个 GUI。我的项目中有两个包 - cryptolib 和 cryptogui。 Cryptolib 包含所有不同的密码作为类,cryptogui 是我的 GUI。

我所有的密码都是我定义的密码类的子类。目前,我在使用以下课程时遇到了困难。

package cryptolib;
public class SubstitutionCipher extends Cipher{
... implementation here ...
}

在我的 GUI 类中,我定义了一个菜单项以使用匿名类切换到替换密码。

package cryptogui;
import cryptolib.*;
public class CryptoSwing extends JFrame {
    private Cipher cipher;
    public CryptoSwing() {
        JMenuItem mntmSubstitution = new JMenuItem("Substitution");
        mntmSubstitution.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                cipher = SubstitutionCipher(txtSubKeyword.getText());
             }
        });
 }

我遇到的问题是,虽然“私人密码密码;”有效,ActionListener 中的 SubstitutionCipher 代码给了我错误

The method SubstitutionCipher(String) is undefined for the type new ActionListener(){}

我从 Swing 导入的类(例如 java.awt.CardLayout)运行良好。我知道这可能是我错过的一些基本问题,但我已经搜索过,但似乎找不到问题。

【问题讨论】:

    标签: java swing user-interface import anonymous-class


    【解决方案1】:
    cipher = SubstitutionCipher(txtSubKeyword.getText());
    

    应该是

    cipher = new SubstitutionCipher(txtSubKeyword.getText());
    

    注意new 关键字。

    【讨论】:

    • 我不敢相信我搞砸了。我得到的一切都恰到好处,这就是我错过的?!