2013-07-31 55 views
5

Tôi đặt JPanel làm contentPane của JFrame.Không thể đặt nền của JPanel trong chương trình Swing của tôi.

Khi tôi sử dụng:

jPanel.setBackground(Color.WHITE); 

Màu trắng không được áp dụng.

Nhưng khi tôi sử dụng:

jFrame.setBackground(Color.WHITE); 

Nó hoạt động ... Tôi ngạc nhiên bởi hành vi này. Nó phải ngược lại, phải không?

SSCCE:

Dưới đây là một SSCCE:

lớp chính:

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

Window Class:

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); 
    } 
} 

container Class:

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

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

kích thước của JPanel là gì? Nó hoàn toàn điền vào khung nội dung? – bas

+0

Để được trợ giúp tốt hơn, hãy sớm đăng một [SSCCE] (http://sscce.org/) – Reimeus

+0

Tôi đã không đặt kích thước của jPanel của tôi. Tôi nghĩ khi bạn thiết lập nó như là một contentPane, nó sẽ tự động có cùng kích thước với jFrame tương ứng. – MarAja

Trả lời

3

Lý do rất đơn giản bao gồm các dòng sau

super.paintComponent(g); 

khi bạn ghi đè paintComponent.

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

Bây giờ nó hoạt động hoàn hảo.

Bạn nên luôn làm điều này trừ khi bạn có lý do rất cụ thể để làm như vậy.

[PS: Thay đổi màu sắc sang màu đỏ hoặc một cái gì đó tối hơn để thấy sự khác biệt như đôi khi nó trở nên khó khăn để phân biệt giữa JFrame 's mặc màu xám và màu trắng]

+0

1+ để được tư vấn tốt. –

1

Với testcode của tôi nó hoạt động theo cách bạn mong đợi nó để làm việc:

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

Người dùng đã yêu cầu sự cố trong mã cụ thể của mình, không phải là phương thức/mã hoạt động. Bất kỳ khi nào bạn đặt một giải pháp thay thế.Good. –

Các vấn đề liên quan