我正在使用这本书Headfirst java,我已经整理了一个我认为能编译好的程序。但是,当窗口创建时,背景或椭圆形不显示。基本paintComponent不被repaint()调用?
import javax.swing.*;
import java.awt.*;
public class setup {
public static void main(String[] args) {
JFrame f = new JFrame();
System.out.println("Created Frame");
JPanel myJPan = new JPanel();
System.out.println("Created Panel");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(300,300);
System.out.println("Set Size");
f.setLocationRelativeTo(null);
f.setContentPane(myJPan);
f.setVisible(true);
System.out.println("Made Visible");
myJPan.repaint();
}
// @Override ???
// "protected void" ??
public void paintComponent(Graphics g) {
// super.paintComponent(); ???
g.fillRect(0,0,300,300);
System.out.println("painted");
int red = (int) (Math.random()*255);
int green = (int) (Math.random()*255);
int blue = (int)(Math.random()*255);
System.out.println("Got Random Colors");
Color randomColor = new Color(red, green, blue);
g.setColor(randomColor);
System.out.println("Set Random Colors");
g.fillOval(70,70,100,100);
System.out.println("Filled Oval");
}
}
'paintComponent'属于'JPanel'' myJPan'类而不是'setup'类 – Reimeus
你实际上并没有重写'myJPan'的'paintComponent'方法。你只需在你的'setup'类中定义一个'paintComponent'方法。 – DannyMo
如果您添加了@ @ Override注解,编译器会告诉您实际上并没有覆盖任何东西。 – DannyMo