2

I started experimenting with JFrame and my first task I wanted to accomplish was drawing a 50px square with the fillRect() or drawRect() method. Unfortunately after running, the program showed a rectangle instead of a square.

This is defenitly not a square

My code:

package javaapp;

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

public class JavaApp extends JFrame{

    public JavaApp() {
        setTitle("Voorbeeld");
        setSize(250, 250);
        setResizable(false);
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }
    public void paint (Graphics g){
        g.fillRect(0, 0, 50, 50);
    }
    public static void main(String[] args) {
        new JavaApp();
    }   
}
call-me
  • 686
  • 9
  • 18
  • "The point of origin in my GUI is off by about 25/26 pixels" This title has nothing to do with JFrame and not even Java. How could I know it was a duplicate? Analise all questions with "Pixel" in it's title name? – call-me Jan 11 '16 at 21:41
  • I don't know, it's a common enough problem with multiple answers. Spending sometime researching the problem might have helped, maybe inspecting the tutorials or docs? The fact it's a duplicate isn't the issue (per say), helping you find the answer is. As you might note, the now "accepted" answer is actually wrong and misleading to other developers that might have a similar issue – MadProgrammer Jan 11 '16 at 21:49

1 Answers1

4

The frame actually starts way at the top left corner. It's simple to just add a JPanel and paint on it instead. Otherwise you could call setUndecorated(true)

class JavaApp extends JFrame {

    public JavaApp() {
        setTitle("Voorbeeld");
        setSize(250, 250);
        setResizable(false);
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        add(new JPanel() {
            protected void paintComponent(Graphics g) {
                g.setColor(Color.BLACK);
                g.clearRect(0, 0, getWidth(), getHeight());
                g.fillRect(0, 0, 50, 50);
            }
        });
    }

    public static void main(String[] args) {
        new JavaApp();
    }
}

Use paintComponent instead.

John E.
  • 418
  • 2
  • 10
  • Or, because top level containers aren't double buffered, use a `JPanel` and override it's `paintComponent` method instead, as outlined in [Performing Custom Painting](http://docs.oracle.com/javase/tutorial/uiswing/painting/) – MadProgrammer Jan 11 '16 at 19:59