0

I have this little bug I haven´t been able to handle. I set the size of the JPanel to be (150,90), but the code in the paintComponent() show its (160,100). Whats wrong? Thanks for your time and help.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Test2 extends JPanel{

    public static void main(String[] args) {

        JFrame window = new JFrame("Test");
        Test2 content = new Test2();
        window.setContentPane(content);
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setLocation(120,70);
        window.pack();
        window.setResizable(false);
        window.setVisible(true);
    }

    Test2(){
        setBackground( new Color(0,120,0) );
        setPreferredSize( new Dimension(150, 90));
        repaint();
    }

    public void paintComponent(Graphics g){
        super.paintComponent(g);
        g.setColor( Color.YELLOW);
        g.drawRect(0, 0, 150, 90);
        System.out.println(this.getWidth());
        System.out.println(this.getHeight());
    }
}

The Console output indicates that the size is (160,90). The yellow rectangle shows the same.

McMoss
  • 31
  • 1
  • 1
    See [Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?](http://stackoverflow.com/q/7229226/418556) (Yes.) In this case, `Test2` should override the preferred size method. Also, for compile time checking, add the `@Override` notation. – Andrew Thompson Aug 27 '15 at 14:49
  • @mcmoss don't forget to accept the answer if it help you – Madhawa Priyashantha Sep 20 '15 at 16:46

1 Answers1

5
    window.pack();
    window.setResizable(false);

Should be:

    window.setResizable(false);
    window.pack();

Changing a window to non-resizable changes the 'chrome' (the wrapper around the outside) of the window - it might become thicker or thinner. If we do it before the call to pack, Swing will handle the changed chrome correctly.

Tips

Community
  • 1
  • 1
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • Thanks Andrew, Can´t say I know why, but it works. Although applying the solution to my bigger problem it didn´t. What did work was deleting window.setResizable(false) from my program. – McMoss Aug 27 '15 at 17:06