2014-02-12 28 views
1

當我運行這個程序時,顏色不會變成藍色。我如何在這種情況下改變顏色?代碼:在此上下文中更改JFrame上的背景顏色?

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

public class Test extends JPanel { 
static void test() { 
    JFrame f = new JFrame("Test"); 
    f.getContentPane().setBackground(Color.blue); 
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    f.getContentPane().add(new Test()); 
    f.setExtendedState(JFrame.MAXIMIZED_BOTH); 
    f.setVisible(true); 
} 

public static void main(String[] args) { 
    SwingUtilities.invokeLater(new Runnable() { 
    public void run() { 
     test(); 
    } 
    }); 
} 
} 
+0

而不是使用的getContentPane(),只是做的setBackground(Color.BLUE); *可能是setBackgroundColor,不記得了,但是使用顏色大寫。* – user2277872

回答

1

我覺得你的新測試()是重疊的背景顏色。

嘗試更改jpanels背景顏色。

1

setBackground工作正常。問題出在JFrame的默認BorderLayout。您添加的唯一組件是TestJPanel,它擴大了JFrame的尺寸,這是由於BorderLayout,最終掩蓋了背景顏色。如果你拿出TestJPanel你會看到背景顏色。

您還可以看到影響,下面,佈局設置爲GridBagLayout的框架和設置preferredSize to the JPanel`

enter image description here

import java.awt.Color; 
import java.awt.Dimension; 
import java.awt.GridBagLayout; 
import javax.swing.*; 
import javax.swing.border.TitledBorder; 

public class Test extends JPanel { 
    public Test() { 
     setBorder(new TitledBorder("Panel size 300, 300")); 
     setBackground(Color.YELLOW); 
    } 

    @Override 
    public Dimension getPreferredSize() { 
     return new Dimension(300, 300); 
    } 

    static void test() { 
     JFrame f = new JFrame("Test"); 
     f.setLayout(new GridBagLayout()); 
     f.getContentPane().setBackground(Color.blue); 
     f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     f.getContentPane().add(new Test()); 
     f.setExtendedState(JFrame.MAXIMIZED_BOTH); 
     f.setVisible(true); 
    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 
      public void run() { 
       test(); 
      } 
     }); 
    } 
} 

原因GridbagLayout作品是因爲它的尊重子組件的preferredSize。正如你可以看到this answer,一些佈局管理器尊重首選大小和一些不

enter image description here

+0

這就對了。 ▲。 –

1

設置佈局JFrame

f.setLayout(new FlowLayout());