0

I have a class Skeleton that makes a Surface and sets the size to 400x400

public class Skeleton extends JFrame {

    public Skeleton() 
    {
        initUI();
    }

    private void initUI()
    {
        setTitle("");
        int height = 400;
        int width = 400;

        add(new Surface());

        setPreferredSize(new Dimension(width + getInsets().left + getInsets().right,
                                        height + getInsets().top + getInsets().bottom));

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
        //setResizable(false);
    }

    public static void main(String[] args) 
    {
        SwingUtilities.invokeLater(new Runnable()
        {

            @Override
            public void run() {

                Skeleton sk = new Skeleton();
                sk.setVisible(true);
            }
        });
    }
}

Then in the surface class I draw a line from (0,0) to (400,400) and when I run the code the bottom end of the diagonal ends off the panel.

class Surface extends JPanel 
{

    private void makediag(Graphics g, int size) 
    {
        Graphics2D g2d = (Graphics2D) g;

        g2d.setColor(Color.blue);
        g2d.drawLine(0, 0, size, size);

    }

    @Override
    public void paintComponent(Graphics g) 
    {
        super.paintComponent(g);
        makediag(g, 400);
    }
}

What am I doing wrong? Is the size of the panel wrong or are the drawing coordinates different?

Souren
  • 47
  • 5

2 Answers2

4

The size of JPanel is wrong because you are setting preferred size for your JFrame.

Best way would be to override JPanels getPreferredSize method and to return your desired dimension.

protected Dimension getPreferredSize() {
    return new Dimension(400, 400);
}

Also, be sure just to call pack for your JFrame. Don't call setXXXSize at all.

Branislav Lazic
  • 14,388
  • 8
  • 60
  • 85
  • 2
    +1, also see [Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing](http://stackoverflow.com/q/7229226/1048330) – tenorsax Nov 16 '13 at 23:25
0

According to the javadoc for pack:

Causes this Window to be sized to fit the preferred size and layouts of its subcomponents.

Therefore the window is supposed to ignore its own preferred size and use the preferred size of its subcomponents. There's no reason to expect setPreferredSize to influence the size of the frame. It seems what you really want to do is to set the preferred size of the Surface to (400,400). That also saves you from having to work with insets.

Geo
  • 750
  • 7
  • 17