Why does this JFrame not end up being blue?

beavoid
beavoid used Ask the Experts™
on
Hi
I'm surprised this JFrame didn't work, an I wonder why. It doesn't draw any blue. What might I have done wrong?

import java.awt.Color;
import java.awt.Graphics;

import javax.swing.*;


public class Merrywin extends Thread{
	
	JFrame jFrame;

	public Merrywin() {
		
		
		
		start();
	}
		
		

		
		
		
	

	public void run() {

		System.out.println("Hi");
		jFrame = new JFrame();   
		jFrame.setBounds(10, 0, 1125, 2436);  
		jFrame.setVisible(true);
		
		Graphics G = jFrame.getGraphics();
		G.setColor(Color.BLUE);
		G.fillRect(0, 0, 1000, 2000);
			
				

	}
		
		
	public static void main(String[] args) {
		System.out.println("Maine");

			Merrywin m = new Merrywin();

	}

}

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2016

Commented:
It does actually, but so quickly you probably won't see it. It's not the way to do custom painting in Java, since what you paint briefly will be painted away again.
See https://docs.oracle.com/javase/tutorial/uiswing/painting/index.html
Distinguished Expert 2018
Commented:
You need to add a new component, and paint the new component, otherwise you won't be able to see the colour (which, as CEJH mentioned, is being painted once and then repainted over).

Try

public class Merrywin {

	JFrame jFrame;

	public Merrywin() {

		run();
	}

	public void run() {

		System.out.println("Hi");
		jFrame = new JFrame();
		jFrame.setBounds(10, 0, 1125, 2436);
		jFrame.add(new APanel());
		jFrame.setVisible(true);

//		Graphics G = jFrame.getGraphics();
//		G.setColor(Color.BLUE);
//		G.fillRect(0, 0, 1000, 2000);

	}

	public static void main(String[] args) {
		System.out.println("Maine");

		Merrywin m = new Merrywin();

	}

}

class APanel extends JPanel {
	protected void paintComponent(Graphics g) {
        super.paintComponent(g);       
        g.setColor(Color.BLUE);
        g.fillRect(0, 0, 1000, 2000);
    }  
}

Open in new window

beavoidSelf Employed

Author

Commented:
Thanks

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial