paintComponent方法没有在Java中调用

Asd*_*eev 3 java swing

我正在做这个非常基本和简单的Swing教程作为我的软件工程课程的第一个作业,并且由于一些非常奇怪的原因,我的JPanel中没有调用paintComponent方法.现在我和Java Swing一起工作过,我从来没有遇到过这样的问题.

我正在使用的教程就在Oracle站点上找到(更容易访问该站点并查看代码,因为它与我的代码相同).

教程链接

任何人都可以向我解释为什么它不适合我?

我的代码:

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);
}
}
Run Code Online (Sandbox Code Playgroud)

Dan*_* D. 5

paintComponent(Graphics g)不是paintComponenet(Graphics g).

至少你super.paintComponent(g)正确地打电话.

如果使用注释对paint*方法进行@Override注释,则会出现编译错误,以帮助您了解正在进行的操作.