2

Hello I'm trying to do some drawing examples in Java using the paintComponent and the Graphics Object. I need a fixed size 'Stage' (400x300) for the drawing and the window/frame "around it".

Here is my setup:

public class MyJFrame extends JFrame{    
    public MyJFrame(){
        //setSize(new Dimension(400,300));
        setBackground(Color.green);
        Stage stage = new Stage();
        add(stage);
        
        this.pack();
        this.setResizable(false);
        this.setVisible(true);
        
        System.out.println(this.size());
        System.out.println(stage.size()); 
    }
}

public class Stage extends JPanel {
    
    public Stage(){
        setPreferredSize(new Dimension(400,300));
        //setSize(new Dimension(400,300)); 
    }
    
    @Override
    protected void paintComponent(Graphics g) {
        g.setColor(Color.BLACK);
        g.fillRect(0, 0, 400, 300); 
    }
}

Out put of the print is :

java.awt.Dimension[width=416,height=338]
java.awt.Dimension[width=400,height=300]

But the result looks like this:
enter image description here

Black part is 400x300 .. not sure from where this extra spacing comes from.
I tried several variation of setSize setPreferredSize and layouts .. but nothing really worked.

P.S any java fiddle out there?

Community
  • 1
  • 1
d.raev
  • 9,216
  • 8
  • 58
  • 79

3 Answers3

4
//this.pack();
this.setResizable(false);
this.pack();
camickr
  • 321,443
  • 19
  • 166
  • 288
3

Two things.

  1. Call pack AFTER you setResizable. This is a (not commonly) known bug
  2. Don't rely on magic numbers. You should be using known values where possible. This will make your life easier should you decide to change these values later.

For example, instead of g.fillRect(0, 0, 400, 300); you should be using g.fillRect(0, 0, getWidth(), getHeight());

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
2

In this case I think you are better off using a BufferedImage as the paint surface and simply displaying that in a JLabel. A simple (animated) example can be seen in this answer.

Community
  • 1
  • 1
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433