Ruben de groot
Ruben de groot

Reputation: 15

Calling a paint or render method from another class - Java

I did allot of research for this problem but couldn't find anything that would help me out. When I run this app, the only thing I will see is an empty JFrame, the expected output is a JFrame with a black rectangle. This is my code, there are two classes.

public class Test {

public static void main(String[] args) {
    Test test = new Test("Frame");
    test.setFrame();
    Window win = new Window(ObjectId.Window, 10, 10, 10, 10);
    win.repaint();
}

private String title;

public Test(String title) {
    this.title = title;
}

private void setFrame() {
    JFrame frame = new JFrame(title);
    frame.setSize(800, 600);
    frame.setResizable(false);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
}

}

And my second class:

public class Window extends Component {

private ObjectId id;

private int x, y;
private int width, height;  

public Window(ObjectId id, int x, int y, int width, int height) {
    this.id = id;

    this.x = x;
    this.y = y;

    this.width = width;
    this.height = height;

}

public void paintComponent(Graphics g) {
    g.setColor(Color.black);
    g.fillRect(x, y, width, height);
}

Thanks

Upvotes: 0

Views: 240

Answers (1)

Lukas Rotter
Lukas Rotter

Reputation: 4188

You didn't add win to the frame ('s contentPane). And you should extend JPanel in the Window-class, not Component.

So if you move Window win = new Window(ObjectId.Window, 10, 10, 10, 10) into the setFrame() method (you don't need the win.repaint()) and call frame.getContentPane().add(win) (or something similar) it will work.

Upvotes: 1

Related Questions