我正在做这个非常基础和简单的 Swing 教程,作为我的软件工程类(class)的第一个作业,由于一些非常奇怪的原因,我的 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);
}
}
最佳答案
是paintComponent(Graphics g)
,不是paintComponenet(Graphics g)
。
至少你正确地调用了 super.paintComponent(g)
。
如果您使用 @Override
注释来注释您的 paint*
方法,您将得到一个编译错误,这将帮助您了解正在发生的事情。
关于java - 没有在 Java 中调用 paintComponent 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14549383/