在匿名类中访问Enclosing类

时间:2014-03-24 01:25:18

标签: java

假设我有一个像这样的

的代码
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;

class GUIExercise {
    private static void createAndShowGUI () {
        JFrame frame = new JFrame("My Demo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel center = new JPanel();
        center.setLayout(new BoxLayout(center, BoxLayout.Y_AXIS));

        JLabel label = new JLabel("Migz");
        label.setHorizontalAlignment(JLabel.CENTER);
        label.setFont(label.getFont().deriveFont(Font.ITALIC | Font.BOLD));

        center.add(label);
        JButton btn = new JButton("Click me");
        btn.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed (ActionEvent e) {
                JOptionPane.showMessageDialog(GUIExercise.this, "Font.ITALIC is " + Font.ITALIC + " and Font.BOLD is " + Font.BOLD + " finally Font.ITALIC | Font.BOLD is " + (Font.ITALIC | Font.BOLD), "Ni Hao", JOptionPane.INFORMATION_MESSAGE);
            }
        });
        center.add(btn);

        frame.getContentPane().add(center, BorderLayout.CENTER);
        frame.pack();
        frame.setSize(frame.getWidth() + 100, frame.getHeight() + 50);
        frame.setVisible(true);
    }

    public static void main (String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run () {
                createAndShowGUI();
            }
        });
    }
}

将GUIExercise.this放在showmessagedialog的第一个参数中会导致错误:非静态变量无法从静态上下文引用。必须做什么?或者我如何访问EnclosingClass?

1 个答案:

答案 0 :(得分:2)

您似乎正在尝试在static方法中使用该代码。您无法从static上下文访问封闭实例,因为没有实例。


这不是问题所在。问题是您正在尝试直接在类的主体中执行该方法。你不能这样做。您必须将它放在一个方法中,可能是您要作为ActionListener接口的一部分覆盖的方法。

btn.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        JOptionPane.showMessageDialog(EnclosingClass.this, "Hello");
    }
});

<击>

(假设EnclosingClassComponent。)