2014-09-19 126 views
0

我是一個初學者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。我爲什麼可以在事件後使用它。這很愚蠢,我想立即着手,我不想按下按鈕。

+5

不要'JFrame'這場平局辦法。改寫'paint'方法。 [Oracle教程:自定義繪畫](http://docs.oracle.com/javase/tutorial/uiswing/painting/index.html) – BackSlash 2014-09-19 09:34:39

+0

什麼錯了,我測試了你的代碼,我在輸出中有一個白色面板框架。這是你的輸出嗎? – Anptk 2014-09-19 09:40:33

+1

你可以先使用調試,看看數字是真正的繪圖。我不確定爲什麼會發生這種情況,但是我認爲在此之後圖像會被重新繪製,這就是爲什麼你會得到空白幀。請糾正我=) – Donvino 2014-09-19 09:46:20

回答

3
  1. 千萬不要用getGraphics()來畫。

  2. 不要試圖和頂層容器烤漆工藝般JFrame

  3. 相反(如圖Performing Custom Painting - 必讀),使用JPanel(或JComponent)並覆蓋其protected void paintComponent(Graphics g)方法。使用該圖形上下文來繪畫。所有的繪畫都應該在圖形上下文中提供,無論是直接在paintComponent方法中編寫代碼,還是調用將對象傳遞給參數的方法。

  4. 覆蓋public Dimension getPreferredSize()JPanel/JComponent給你繪畫表面的首選大小。將pabel添加到框架,然後pack()您的框架。

    public class DrawPanel extends JPanel { 
        @Override 
        protected void paintComponent(Graphics g) { 
         super.paintComponent(g); 
         g.draw... // do all your drawing here 
        } 
        @Override 
        public Dimension getPreferredSize() { 
         return new Dimension(400, 400); 
        } 
    } 
    

重要:您必須閱讀的風俗畫的聯繫張貼有關繪畫的另一個問題之前,或者你會得到一個非常好的:-)

+0

你能解釋爲什麼我不能使用'getGraphics()',爲什麼我必須重載'paintComponent()'。 – botenvouwer 2014-09-19 10:09:30

+2

1. getGraphics()存在一個調用,因爲它不會持久化任何東西。它是組件塗漆的一部分。這些方法被調用,所以你不必自己調用它們。閱讀鏈接,他們給出了很好的解釋 – 2014-09-19 10:12:11