我是一個初學者JAVA和我打破我的頭以下問題:爲什麼不會JAVA圖形繪製
爲什麼這個代碼不畫
import ...
public class tekening extends JFrame{
private JPanel p;
private Graphics g;
tekening(){
setLayout(new FlowLayout());
p = new JPanel();
p.setPreferredSize(new Dimension(350, 350));
p.setBackground(Color.WHITE);
add(p);
setLocationByPlatform(true);
setSize(400, 400);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
g = p.getGraphics();
g.setColor(Color.BLACK);
g.drawRect(30, 30, 80, 40);
g.drawLine(10, 10, 40, 50);
}
}
爲什麼這段代碼畫了嗎
import ...
public class tekenclasse extends JFrame implements ActionListener{
private JPanel p;
private Graphics g;
private JButton button1;
tekenclasse(){
setLayout(new FlowLayout());
button1 = new JButton("Knop 1");
button1.addActionListener(this);
add(button1);
p = new JPanel();
p.setPreferredSize(new Dimension(350, 350));
p.setBackground(Color.WHITE);
add(p);
setLocationByPlatform(true);
setSize(400, 400);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e){
g = p.getGraphics();
g.setColor(Color.BLACK);
g.drawRect(30, 30, 80, 40);
g.drawLine(10, 10, 40, 50);
}
}
對我來說這完全是奇怪的。爲什麼我不能在構造函數中使用Graphics。我爲什麼可以在事件後使用它。這很愚蠢,我想立即着手,我不想按下按鈕。
不要'JFrame'這場平局辦法。改寫'paint'方法。 [Oracle教程:自定義繪畫](http://docs.oracle.com/javase/tutorial/uiswing/painting/index.html) – BackSlash 2014-09-19 09:34:39
什麼錯了,我測試了你的代碼,我在輸出中有一個白色面板框架。這是你的輸出嗎? – Anptk 2014-09-19 09:40:33
你可以先使用調試,看看數字是真正的繪圖。我不確定爲什麼會發生這種情況,但是我認爲在此之後圖像會被重新繪製,這就是爲什麼你會得到空白幀。請糾正我=) – Donvino 2014-09-19 09:46:20