为什么我的 JPanel 颜色填满了整个窗口 GUI?不知道是代码有问题还是编译器有问题?

问题描述 投票:0回答:1

窗口出现如下: 在此输入图片描述 这是我的代码:

import java.awt.Color;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class gui2 {

    public static void main(String[] args) {
        JPanel bluepanel = new JPanel();
        bluepanel.setBackground(Color.blue);
        bluepanel.setBounds(0, 0, 250, 250);
        
        JPanel greenpanel = new JPanel();
        greenpanel.setBackground(Color.green);
        greenpanel.setBounds(250, 0, 250, 250);
        
        JPanel redpanel = new JPanel();
        redpanel.setBackground(Color.red);
        redpanel.setBounds(0, 250, 250, 250);
        
        JFrame frame = new JFrame();
        frame.setTitle("what?");
        frame.setSize(500,500);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        frame.add(bluepanel);
        frame.add(greenpanel);
        frame.add(redpanel);
    }

}

我曾尝试添加新的JPanel甚至设置背景颜色,但都无法解决问题。

java user-interface jframe jpanel
1个回答
0
投票

您应该将 JFrame 布局设置为 null。

这是更新的代码。

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

public class gui2 {

    public static void main(String[] args) {
        // Create panels
        JPanel bluepanel = new JPanel();
        bluepanel.setBackground(Color.blue);
        bluepanel.setBounds(0, 0, 250, 250);
        
        JPanel greenpanel = new JPanel();
        greenpanel.setBackground(Color.green);
        greenpanel.setBounds(250, 0, 250, 250);
        
        JPanel redpanel = new JPanel();
        redpanel.setBackground(Color.red);
        redpanel.setBounds(0, 250, 250, 250);
        
        // Create frame
        JFrame frame = new JFrame();
        frame.setTitle("what?");
        frame.setSize(500, 500);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(null); // Set layout manager to null
        frame.add(bluepanel);
        frame.add(greenpanel);
        frame.add(redpanel);
        frame.setVisible(true);
    }
} 
© www.soinside.com 2019 - 2024. All rights reserved.