2014-02-12 23 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());