我正在使用這本書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