我正在做一份非常基础和简单的Swing教程,这是我软件工程课程的第一个作业。但出现了一个非常奇怪的问题,我的JPanel中的paintComponent方法没有被调用。我之前使用过Java Swing,从未遇到过这样的问题。
我使用的教程可以在Oracle网站上找到(因为它是我所拥有的相同代码,所以更容易去该网站查看)。 教程链接 请问有人能解释一下为什么对我不起作用吗?
我的代码:
我使用的教程可以在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);
}
}
@Override
注释(我建议他这样做),否则它应该可以编译通过。 - Hovercraft Full Of Eels