Skip to main content
gamedev.net
🔒 Locked

[java] Componant not being displayed

Started by Esqulax Nov 28, 2008 at 7:43 PM 4 replies 1.1k views
Original Post
Esqulax
Esqulax
Hiya New to all this.. teaching myself... (yadda yadda) I have this basic code, it compiles OK, but when it runs, the frame appears, but the rectangle doesnt, if anyone can spot the flaw, it would be awesome

package app1;

import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;

public class MainClass extends JFrame {

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

public MainClass() {
 this.setSize(800, 800);
 this.setTitle("Awesome");
 this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

 
this.add(new DrawIt());
 
 this.setVisible(true);
}

private class DrawIt extends JComponent{

    public void Paint(Graphics g){

        Graphics2D g2 = (Graphics2D)g;

        Shape s = new Rectangle2D.Float(10,10,40,40);
        g2.setPaint(Color.RED);
        g2.draw(s);
}
    
}
}

someboddy
someboddy
I'm not sure if this is the problem, but you are supposed to add your components to the content pane instead of the frame when you use swing?

try replacing "this.add(new DrawIt());" with "this.getContentPane().add(new DrawIt());"
-----------------------------------------Everyboddy need someboddy!
Esqulax
Esqulax
Same result from that code unfortunatly

I thought that, but apparently it is possible to draw directly to the Frame, just not very efficient.

I've also tried filling the rect with a random colour, to be sure that its not just the same colour as the BG, but to no avail :s
Esqulax
Esqulax
Ok, well, on a whim i changed:

public void Paint(Graphics g)

to

public void paintComponent(Graphics g)

And it worked :)

Thanks for replying :)
elFarto
elFarto
Actually, changing:

public void Paint(Graphics g)

to

public void paint(Graphics g)

should work too.

Regards
elFarto
leif_dragon
leif_dragon
definitely use 'paint(Graphics g)' over 'paintComponent(Graphics g)'

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.