4

我正在尝试创建自己的扩展窗口类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

4 回答 4

7

在内部类中,this如果您需要获取对外部类的引用,则需要在使用外部类的类名之前添加:例如,使用

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

顺便说一句,在大多数情况下,您真的不想在此处扩展 JFrame。

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

        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...
于 2013-03-23T14:48:11.433 回答
3

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

OuterClass.this.foo();
于 2013-03-23T14:50:24.117 回答
1

因为您使用的是anonymous class,this将引用该类,在本例中为ActionListener. 因为您ActionListener没有诸如 之类的方法setUndecorated,所以这会给您一个编译错误。

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

于 2013-03-23T14:50:45.977 回答
1

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

MyWindow.this
于 2013-03-23T14:51:35.973 回答