0

A friend was showing me JFrame and JPanel stuff, but my code wasn't working as we expected. I made a JFrame "window" and two JPanels, "container" and "canvas"

window = new JFrame();
window.setSize(width, height);  
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
window.setLocationRelativeTo(null);
window.setVisible(true);

JPanel container = new JPanel() {};

JPanel canvas = new JPanel() { //box
        public void paint(Graphics g) {
            super.paint(g);
                    
                    
            g.setColor(Color.GREEN);
            g.fillRect(0, 0, width, height); //width and height are screen's width and height
        }
    };
            

he told me that I should add all my panels to the Container, then add the container to the window, which made sense to me. But when I did:

container.add(canvas);
window.add(container);

it created a very small green square in the top middle of the screen, when it should have filled the entire screen program window

Strangely enough, when I just did:

window.add(canvas);

it worked perfectly as intended. Why is this happening, and how can I fix it? if its useful, I'm using Eclipse IDE. Thanks!

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
Henry
  • 55
  • 1
  • 1
  • 5
  • 3
    You should start by having a look at [Creating a GUI With Swing](https://docs.oracle.com/javase/tutorial/uiswing/), paying close attention to [Laying Out Components Within a Container](https://docs.oracle.com/javase/tutorial/uiswing/layout/index.html) – MadProgrammer Jan 26 '22 at 02:58
  • 2
    You should also have a look at [Painting in AWT and Swing](https://www.oracle.com/java/technologies/painting.html) and [Performing Custom Painting](https://docs.oracle.com/javase/tutorial/uiswing/painting/index.html) as you're doing it wrong (or in a less the advisable way) and you could just use `canvas.setBackground(Color.GREEN)` and get the same result – MadProgrammer Jan 26 '22 at 03:01

0 Answers0