2014-10-07 117 views
1

好吧, 我不是很熟悉awt api,所以這對我來說是非常新的東西。我有從我的主類運行這些方法來創建我的jframe。在我的createframe方法下,背景色似乎不適用於框架。任何幫助?JFrame背景顏色不顯示

這裏是我的框架類

import java.awt.Color; 
import java.awt.Container; 

import javax.swing.JFrame; 
import javax.swing.JPanel; 

public class FrameClass { 

     JFrame frame; 

     public FrameClass(String framename) { 
       frame = new JFrame(framename); 
     } 

     public void CreateFrame() { 
      Color c = new Color(0,255,0); 
      Container con = frame.getContentPane(); 
      con.setBackground(c); 
      frame.getContentPane().setBackground(c); 
       frame.setSize(400, 250); // Set the JFrame size when it is on the login screen 
       frame.setLocationRelativeTo(null); // Center the JFrame 

       /* Display the frame */ 
       frame.setVisible(true); 
     } 

     public void AddPanel() { 
       JPanel ButtonsPanel = new JPanel(); 
       ButtonsPanel.setVisible(true); 
       frame.add(ButtonsPanel); 
     } 
} 

這是我的主類

public class Admin { 

    public static FrameClass FrameObject = new FrameClass("ITWebKit Admin Panel"); 
    public static Database DatabaseObject = new Database(); 

    public static void main(String args[]) { 
     FrameObject.CreateFrame(); 
     FrameObject.AddPanel(); 
    } 
} 

回答

1

ButtonsPanel被掩蓋框架的內容窗格(其中你設置的背景)。您可以將ButtonsPanelopaque屬性設置爲false,也可以將背景設置爲ButtonsPanel

爲什麼發生這種情況

默認的內容窗格有BorderLayoutBorderLayout將拉伸ButtonPanel以適應其尺寸。如果要將內容窗格/框架的佈局管理器更改爲FlowLayout(其將而不是伸展面板),您將看到背景。

其他注意事項:

  • FrameObject.CreateFrame(); FrameObject.AddPanel();。這會在添加組件之前將幀設置爲可見。一般你想添加組件,然後設置框架可見。

  • 遵循Java命名約定。方法名稱和變量名稱以小寫字母開頭。

  • Swing程序應該在事件調度線程(EDT)上啓動。見Initial Threads

+1

噢,謝謝。不明白,它可能會被過分控制。 – Andrew 2014-10-07 06:27:51