Ahmed Tawfik
Ahmed Tawfik

Reputation: 63

Java - paintComponent won't show drawings on JPanel

I've gotten stuck trying to draw on a JPanel. I've learned how to create a JFrame, a JPanel, add event handlers, do the same in applets, and some other basic GUI development. But everytime I try to draw on a JPanel using the paintComponent(Graphics g) or paint(Graphics g) methods, nothing shows up. Buttons, as well as other JComponents, show up just fine. But g.drawString, g.drawRect, etc result in a blank JFrame window.

Here is my code:

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

public class Game extends JPanel {
    public static void main(String[] args) {
        new Game().game();
    }

    JPanel panel;
    JButton button2;
    JButton button;

    public void game() {
        panel = new JPanel();
        button = new JButton("Ok");
        panel.setLayout(new FlowLayout());
        panel.add(button);

        button2 = new JButton("Cancel");

        JFrame frame = new JFrame("Game");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(500,500);
        frame.setResizable(false);
        frame.add(panel);

        frame.setVisible(true); 
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawString("hi",100,100);
        g.fillRect(100,50,200,300)
    }
}

Upvotes: 2

Views: 1676

Answers (1)

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81684

The JPanel you're adding to your JFrame is a plain vanilla JPanel, not an instance of Game, your custom class that contains the paintComponent() method. YOu need to change that one line to

JPanel panel = new Game();

and you should see a difference immediately!

The instance of Game you create in main() isn't being used for anything, other than calling the game() method. You could use it, if you wanted, by doing this instead:

JPanel panel = this;

and then proceeding as before.

Upvotes: 6

Related Questions