[英]Why cant I change color of my JFRame background when I use setLayout()?
I try to set background color to red for JFrame while keeping white color to JPanel.我尝试将 JFrame 的背景颜色设置为红色,同时将白色设置为 JPanel。 But it doesnt work with setLayout somehow
但它以某种方式不适用于 setLayout
private void buildGraphics(){
JFrame frame = new JFrame();
setTitle("Application");
setBounds(100, 100, 600, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(null);
frame.setBackground(Color.red);
JPanel panel = new JPanel();
panel.setBounds(50, 50, 500, 70);
panel.setBackground(Color.white);
panel.setBorder(BorderFactory.createTitledBorder("Click to choose..."));
panel.add(button1);
panel.add(button2);
panel.add(button3);
getContentPane().add(panel);
}
You already have a frame (your class is extending JFrame
, so it IS a JFrame
) and buildGraphics()
has to build the existing frame you don't have to create a new one:您已经有一个框架(您的类正在扩展
JFrame
,因此它是一个JFrame
)并且buildGraphics()
必须构建现有框架,您不必创建新框架:
private void buildGraphics() {
this.setTitle("Application");
this.setBounds(100, 100, 600, 400);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.getContentPane().setLayout(null);
this.setBackground(Color.red);
JPanel panel = new JPanel();
panel.setBounds(50, 50, 500, 70);
panel.setBackground(Color.white);
panel.setBorder(BorderFactory.createTitledBorder("Click to choose..."));
panel.add(button1);
panel.add(button2);
panel.add(button3);
this.getContentPane().add(panel);
}
Ok, I now created another JPanel and put my first one inside to control background color好的,我现在创建了另一个 JPanel 并将我的第一个放在里面来控制背景颜色
JFrame frame = new JFrame();
setTitle(" Application");
setBounds(100, 100, 600, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(null);
JPanel panelMain = new JPanel();
panelMain.setBounds(5, 5, 595, 395);
panelMain.setBackground(Color.red);
getContentPane().add(panelMain);
JPanel panel = new JPanel();
panel.setBounds(50, 50, 500, 70);
panel.setBackground(Color.white);
panel.setBorder(BorderFactory.createTitledBorder("What would you like to do?"));
panel.add(button1);
panel.add(button2);
panel.add(button3);
panelMain.add(panel);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.