'this'关键字的范围问题

时间:2013-03-23 14:47:34

标签: java swing jframe actionlistener

我正在尝试创建自己的窗口类,扩展JFrame。但是,我遇到了fullScreenBtn的动作侦听器的问题。在撰写ActionListener.actionPerformed功能时,我无法使用this关键字,因为它引用了new ActionListener。我如何引用MyWindow的实例?

public class MyWindow extends JFrame {
    private static GraphicsEnvironment gEnv = GraphicsEnvironment.getLocalGraphicsEnvironment();
    private static GraphicsDevice gDev = gEnv.getDefaultScreenDevice();
    private static JPanel toolbar = new JPanel();
    private static JButton fullScreenBtn = new JButton("Show Full Screen");
    private static boolean isFullScreen = false;

    public MyWindow() {
        toolbar.setLayout(new FlowLayout());
        this.getContentPane().add(toolbar, BorderLayout.PAGE_START);

        fullScreenBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // Toggle full screen window
                this.setUndecorated(!isFullScreen);
                this.setResizable(isFullScreen);
                gDev.setFullScreenWindow(this);

                isFullScreen = !isFullScreen;

                if (isFullScreen) {
                    fullScreenBtn.setText("Show Windowed");
                } else {
                    fullScreenBtn.setText("Show Full Screen");
                }
            }
        });

        this.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent windowEvent) {
                this.dispose();
                System.exit(0);
            }
        });
    }
}

4 个答案:

答案 0 :(得分:7)

在内部类中,如果需要获取对外部类的引用,则需要将this的使用前置为外部类的类名:例如,使用

MyWindow.this.setUndecorated(...)` 
//  etc...

顺便说一下,你真的不想在这里扩展JFrame,在大多数情况下。

此外,保存JButton的祖先窗口可以通过其他方式获得,例如通过SwingUtilities.getWindowAncestor(theButton)。即,

        public void actionPerformed(ActionEvent e) {
            Object source = e.getSource();
            if (source instanceof JButton) {
              JButton button = (button) source;
              Window ancestorWin = SwingUtilities.getAncestorWindow(button);
              ancestorWin.setUndecorated(!isFullScreen);
              ancestorWin.setResizable(isFullScreen);
              // etc...

或者如果您最清楚地知道祖先窗口是JFrame:

        public void actionPerformed(ActionEvent e) {
            Object source = e.getSource();
            if (source instanceof JButton) {
              JButton button = (button) source;

              JFrame ancestorWin = (JFrame) SwingUtilities.getAncestorWindow(button);
              ancestorWin.setUndecorated(!isFullScreen);
              ancestorWin.setResizable(isFullScreen);
              // etc...

答案 1 :(得分:3)

这是从内部类或匿名类访问封闭类的实例的语法:

OuterClass.this.foo();

答案 2 :(得分:1)

由于您使用的是anonymous classthis会引用该类,在本例中为ActionListener。由于您的ActionListener没有setUndecorated等方法,因此会出现编译错误。

您要做的是使用MyWindow.this,然后使用MyWindow的任何方法。

答案 3 :(得分:1)

您还需要通过指定外部类来访问this,在您的情况下,它必须如下所示:

MyWindow.this