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) {
}
}
kích thước của JPanel là gì? Nó hoàn toàn điền vào khung nội dung? – bas
Để được trợ giúp tốt hơn, hãy sớm đăng một [SSCCE] (http://sscce.org/) – Reimeus
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