tags:

views:

123

answers:

2

I want to do some drawing in a JPanel but the enclosing JFrame size doesn't seem to match where I've asked the coordinates to be drawn.

In my example code, the JFrame size is set to (700, 700) and the last point is drawn at (600, 600). I would expect this point to be drawn 100 pixels away from the right and bottom edges but it isn't (please see screenshot).

alt text

Here's the code I'm using:

import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Scratch extends JPanel {

    static int frameWidth = 700;
    static int frameHeight = 700;

    public static void main(String[] args) {

    JFrame frame = new JFrame();

    frame.setSize(frameWidth, frameHeight);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    Scratch scratch = new Scratch();

    frame.getContentPane().add(scratch);

    frame.setVisible(true);

    }

    @Override
    public void paintComponent(Graphics g) {

    g.drawRect(100, 100, 1, 1);

    g.drawString("100", 100, 100);

    g.drawRect(200, 200, 1, 1);

    g.drawString("200", 200, 200);

    g.drawRect(300, 300, 1, 1);

    g.drawString("300", 300, 300);

    g.drawRect(400, 400, 1, 1);

    g.drawString("400", 400, 400);

    g.drawRect(500, 500, 1, 1);

    g.drawString("500", 500, 500);

    g.drawRect(600, 600, 1, 1);

    g.drawString("600", 600, 600);


    }

}
+3  A: 

Your JFrame is probably 700x700 if you include the window decorations. Since your paintComponent() method belongs to the panel inside your JFrame, all the items will be drawn with an origin at the upper left corner of the panel, not the upper left corner of the JFrame.

Possible fix is to make your panel 700x700 and make the JFrame resize accordingly.

wds
Yup, including the title bar the frame is exactly 700px on my mac.
extraneon
+2  A: 

Only a guess:

public class Scratch extends JPanel {

    static int frameWidth = 700;
    static int frameHeight = 700;

    public static void main(String[] args) {

    JFrame frame = new JFrame();

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    Scratch scratch = new Scratch();
    scratch.setSize(frameWidth, frameHeight);

    frame.getContentPane().add(scratch);

    frame.pack();
    frame.setVisible(true);

    }
PeterMmm
Thanks, I didn't know about the pack method. To make it work you have to set the preferredSize for scratch too, but pretty much what you said.
Fredrick Pennachi
I think the trick is not only the pack, but setting the size of the scratch/panel in stead of the frame.
extraneon