Why are Graphics2D rectangles not displayed?

278 views Asked by At

I need to be able to display filled rectangles for the program i am creating, however the following code produces the following GUI with only the black text 'test' after calling start then change, could anyone explayin why please?

package core;

import java.awt.Color;
import java.awt.Graphics2D;
import javax.swing.JFrame;

@SuppressWarnings("serial")
public class GUI extends JFrame{

private Graphics2D g;
private int[][][] clickable;

public void start(){

    this.setSize(500, 500);
    this.setTitle("Placeholder");
    this.setVisible(true);
    g = (Graphics2D) this.getGraphics();
}       

public void change(String[] fields, int type[], boolean forwards){
    g.setColor(new Color(28,35,57));
    g.drawRect(0, 0, 100, 100);
    g.drawRect(50, 50, 150, 150);
    g.fillRect(0, 0, 100, 100);
    g.drawString("test", 300, 300);     
}
}

And here is what it looks like ..

output

1

There are 1 answers

0
Wojciech Tomczyk On

Drawing on Swing components (like JFrame) works only in onPaint event. The event can be fired using repaint() method. This event fires automatically when frame needs to be painted. To implement this event behavior override paint() method.

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

public class GUI extends JFrame{

    private Graphics2D g;

    public void start(){
        this.setSize(500, 500);
        this.setTitle("Placeholder");
        this.setVisible(true);
    }       

    public void change(){
        g.setColor(new Color(28,35,57));
        g.drawRect(0, 0, 100, 100);
        g.drawRect(50, 50, 150, 150);
        g.fillRect(0, 0, 100, 100);
        g.drawString("test", 300, 300);
    }

    public void paint(Graphics g2d){
        g = (Graphics2D) g2d;
        change();
    }

    public static void main(String[] args){
        GUI frame = new GUI();
        frame.start();
    }

}