Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

why did my color of JPanel fill up all the window gui? I didn't know if there's something wrong in the code or the compiler?

the window appeared like this:
enter image description here
this is my code:

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

}

I had tried to add new JPanel or even setBackground Color, but it cannot solve the problem.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You should set JFrame layout to null.

Here is updated code.

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);
    }
} 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading