Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

paintComponent method not being called in Java

Tags:

java

swing

I'm doing this very basic and simple Swing tutorial as the first assignment from my software engineering course, and for some very strange reason, the paintComponent method isn't being invoked in my JPanel. Now I've worked with Java Swing in the past and I've never had any issues like this.

The tutorial I am using is found right on the Oracle site(easier to go to the site and look at the code since it's the same code I have).

Tutorial Link

Can anyone please explain to me why it isn't working for me?

My code:

import javax.swing.SwingUtilities;
import javax.swing.JFrame;
import javax.swing.JPanel    
import javax.swing.BorderFactory;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;

public class PaintDemo {

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            createGUI();
        }
    });
}

private static void createGUI() {
    System.out.println("Created GUI on EDT? "+
            SwingUtilities.isEventDispatchThread());
    JFrame frame = new JFrame("Yay, first 2102 lab!!");
    frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);        // allows to close the program
    DemoPanel panel = new DemoPanel();
    frame.add(panel);
    frame.pack();
    frame.setVisible(true);
}
}

class DemoPanel extends JPanel {

public DemoPanel() {
    setBorder(BorderFactory.createLineBorder(Color.BLACK));
}

public Dimension getPreferredSize() {
    return new Dimension(250,200);
}

public void paintComponenet(Graphics g) {
    super.paintComponent(g);
    g.drawString("This is my custom panel!",10,20);
}
}
like image 788
mzbhura Avatar asked Mar 17 '26 18:03

mzbhura


1 Answers

It is paintComponent(Graphics g), not paintComponenet(Graphics g).

At least you are calling the super.paintComponent(g) correctly.

If you annotate your paint* method with the @Override annotation, you will get a compile error that will help you understand what is going on.

like image 153
Dan D. Avatar answered Mar 20 '26 07:03

Dan D.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!