2013-03-23 82 views
4

我想創建自己的窗口類,它擴展了JFrame。但是,我對fullScreenBtn的動作偵聽器存在問題。在編寫ActionListener.actionPerformed函數時,我無法使用this關鍵字,因爲它指的是new ActionListener。我如何參考MyWindow的實例?'this'的範圍問題關鍵字

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); 
      } 
     }); 
    } 
} 

回答

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... 
+0

只是投票關閉這個問題,這是一個明顯的重複。 – 2013-03-23 14:49:52

+0

感謝您的快速回復!我知道必須有一個簡單的方法來做到這一點。你會如何推薦創建這種類而不擴展JFrame? – MTCoster 2013-03-23 14:51:17

+0

@MTCoster:請參閱編輯。 – 2013-03-23 14:52:55

3

這是一個內部類或anonymous-訪問封閉類的實例的語法類:

OuterClass.this.foo(); 
1

由於您使用的是anonymous classthis將指類,在這種情況下,ActionListener。因爲你的ActionListener沒有方法,如setUndecorated,這會給你一個編譯錯誤。

你想要做的是使用MyWindow.this,其次是任何方法MyWindow

1

您將需要通過指定的外部類也一樣,在你的情況下,它是類似如下訪問this

MyWindow.this