2013-07-31 18 views
5

JPanelをmy JFrameのcontentPaneとして設定しました。SwanプログラムでJPanelの背景を設定できません。

私が使用:

jPanel.setBackground(Color.WHITE); 

白い色は適用されません。

しかし、ときに私が使用します。

jFrame.setBackground(Color.WHITE); 

それは私がこの行動に驚いています...動作します。それは反対でなければならないのですか?

SSCCE:ここ

がSSCCEです:

メインクラス:

public class Main { 
    public static void main(String[] args) { 
     Window win = new Window(); 
    } 
} 

ウィンドウクラス:

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

public class Window extends JFrame { 
    private Container mainContainer = new Container(); 

    public Window(){ 
     super(); 
     this.setTitle("My Paint"); 
     this.setSize(720, 576); 
     this.setLocationRelativeTo(null); 
     this.setResizable(true); 
     this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     mainContainer.setBackground(Color.WHITE); //Doesn't work whereas this.setBackground(Color.WHITE) works 
     this.setContentPane(mainContainer); 
     this.setVisible(true); 
    } 
} 

コンテナクラス:

import java.awt.Graphics; 
import javax.swing.JPanel; 

public class Container extends JPanel { 
    public Container() { 
     super(); 
    } 
    public void paintComponent(Graphics g) { 
    } 
} 
私testcodeで
+0

のJPanelのサイズは何か?それはコンテンツペインを完全に埋めますか? – bas

+0

すぐに役立つように[SSCCE](http://sscce.org/) – Reimeus

+0

私はjPanelのサイズを設定しませんでした。 contentPaneとして設定すると、自動的に対応するjFrameと同じサイズになると思いました。 – MarAja

答えて

3

理由は非常に簡単です、あなたがpaintComponentをオーバーライドする際に次の行

super.paintComponent(g); 

が含まれます。

public void paintComponent(Graphics g) { 
     super.paintComponent(g); 
    } 

これで完全に動作します。

非常に具体的な理由がある場合を除いて、常にこれを行う必要があります。

[PS:時々それはJFrame年代の間、既定灰色と白の色を区別することが困難になる違いに気づくために赤または暗いものに色を変更]

+0

良いアドバイスのために1+ –

1

それはあなたがそれが動作するように期待されるように動作します:

public class Main { 

     public static void main(String[] args) { 

      JFrame f = new JFrame(); 
      f.setSize(new Dimension(400,400)); 
      f.setLocationRelativeTo(null); 

      JPanel p = new JPanel(); 
      p.setSize(new Dimension(20,20)); 
      p.setLocation(20, 20); 

      //comment these lines out as you wish. none, both, one or the other 
      p.setBackground(Color.WHITE); 
      f.setBackground(Color.BLUE); 

      f.setContentPane(p); 

      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
      f.setVisible(true); 

     } 
     } 
+0

ユーザーは特定のコードで問題を求めていましたが、動作しているメソッド/コードではありませんでした。 –

関連する問題