2017-10-18 83 views
0

我在使用IntelliJ最新社區版開發的Windows機器上使用Java8。爲了使JFrame能夠全屏顯示,我在下面的解決方案中找到了我想要驗證的一種不同行爲。JFrame在全屏幕沒有undecorated

解決方案,我從JFrame full screen

了按照該解決方案,我需要放三線以下,使JFrame的全屏:

frame.setExtendedState(JFrame.MAXIMIZED_BOTH); 
frame.setUndecorated(true); 
frame.setVisible(true); 

但在項目中,我創建了一個類AppFrame.java那擴展JFrame。而在默認的構造函數中,我設置了一些基本屬性,如字體等,重要的是可見性爲true。

import javax.swing.*; 
import java.awt.*; 

public class AppFrame extends JFrame { 

    AppFrame() { 
     Font baseFont = new Font("Dialog", Font.PLAIN, 12); 
     setFont(baseFont); 
     setLocationRelativeTo(null); 
     setBackground(Color.WHITE); 
     setForeground(Color.black); 
     setLayout(new FlowLayout()); 
     setVisible(true); 
     setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); 
    } 
} 

而且在擴展AppFrame當我試圖把上述三條線(帶或不帶調用setVisible,這已經是從AppFrame推出),將其最大化得到以下錯誤類:

Exception in thread "main" java.awt.IllegalComponentStateException: The frame is displayable. at java.awt.Frame.setUndecorated(Frame.java:923) 

作爲解決方案的一部分(我想驗證) - 通過實驗我從AppFrame.java中刪除了setVisible(true)並且它能夠工作,但是這會影響所有擴展AppFrame的類,所以我從我的類中刪除了frame.setUndecorated(true);,並將setVisible在AppFrame中。異常消失了。另外frame.setUndecorated(true);我相信會刪除JFrame的標題欄。

此外,以下是摘錄的javadoc JFrame的:

A frame may have its native decorations (i.e. Frame and Titlebar) turned off with setUndecorated. This can only be done while the frame is not displayable.

這將是巨大的,如果有人可以驗證此行爲。

+2

我不確定您希望我們驗證什麼,文檔非常清晰 – MadProgrammer

+2

*「我從AppFrame.java中刪除了setVisible(true)」* - I會認爲這是一件好事,因爲它不應該由'AppFrame'來決定應該何時顯示它,這是一個最好留給子類的實現細節 – MadProgrammer

+1

如果你想最大化一個窗口,你可以使用['setExtendedState'](https://docs.oracle.com/javase/8/docs/api/java/awt/Frame.html#setExtendedState-int-) – MadProgrammer

回答

0

通過設計,您必須在setVisible之前且僅在setVisible之前調用setUndecorated。所以你別無選擇,只能從基類調用setVisible中刪除,並且每次都在子類中調用它。

+0

也是正常的做法(?)在invokeLater的構造函數外部調用setVisible。 –

+0

「沒有其他選擇」是一個不準確的陳述,正如我的答案所強調的那樣。在任何編程語言(包括ASM)中,零參數初始化器都不是必需的(據我所知)。 – Wayne

0

修改初始值設定項以使用參數。 AppFrame() {應改爲AppFrame(boolean undecorated, boolean visible) {然後在初始化添加setUndecorated(undecorated);setVisible(visible);

完整的解決方案:

import javax.swing.*; 
import java.awt.*; 

public class AppFrame extends JFrame { 

    AppFrame(boolean undecorated, boolean visible) { 
     Font baseFont = new Font("Dialog", Font.PLAIN, 12); 
     setFont(baseFont); 
     setLocationRelativeTo(null); 
     setBackground(Color.WHITE); 
     setForeground(Color.black); 
     setLayout(new FlowLayout()); 
     setExtendedState(JFrame.MAXIMIZED_BOTH); 
     setUndecorated(undecorated); 
     setVisible(visible); 
     setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); 
    } 
} 

在問候:

A frame may have its native decorations (i.e. Frame and Titlebar) turned off with setUndecorated. This can only be done while the frame is not displayable.

這只是說,你必須這樣做在致電setVisible(true);之前。要確定您是否可以安全地撥打setUndecorated,可以使用if (!isDisplayable()) { ... }