我正在做这个非常基本和简单的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);
}
}
答案 0 :(得分:5)
是paintComponent(Graphics g)
,而不是paintComponenet(Graphics g)
。
至少你正确地呼叫super.paintComponent(g)
。
如果使用paint*
注释对@Override
方法进行注释,则会出现编译错误,以帮助您了解正在发生的事情。