2010-01-25 92 views
1

我無法得到這個橢圓在JFrame上繪圖。在Jframe上繪圖

static JFrame frame = new JFrame("New Frame"); 
public static void main(String[] args) { 
    makeframe(); 
    paint(10,10,30,30); 
} 

//make frame 
public static void makeframe(){ 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    JLabel emptyLabel = new JLabel(""); 
    emptyLabel.setPreferredSize(new Dimension(375, 300)); 
    frame.getContentPane().add(emptyLabel , BorderLayout.CENTER); 
    frame.pack(); 
    frame.setVisible(true); 
} 

// draw oval 
public static void paint(int x,int y,int XSIZE,int YSIZE) { 
    Graphics g = frame.getGraphics(); 
    g.setColor(Color.red); 
    g.fillOval(x, y, XSIZE, YSIZE); 
    g.dispose(); 
} 

該框架顯示,但沒有畫任何東西。我在這裏做錯了什麼?

回答

8

您已經創建了不靜態方法重寫paint方法。現在,其他人已經指出,你需要重寫paintComponent等,但一個快速解決你需要這樣做:

public class MyFrame extends JFrame{ 

    public MyFrame(){ 
      super("My Frame"); 

      //you can set the content pane of the frame 
      //to your custom class. 

      setContentPane(new DrawPane()); 

      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

      setSize(400, 400); 

      setVisible(true); 
    } 

     //create a component that you can actually draw on. 
     class DrawPane extends JPanel{ 
     public void paintComponent(Graphics g){ 
      //draw on g here e.g. 
      g.fillRect(20, 20, 100, 200); 
     } 
    } 

    public static void main(String args[]){ 
      new MyFrame(); 
    } 

    } 

然而,正如有人指出的......畫上一個JFrame是非常棘手的。最好使用JPanel。

+0

這是真正的問題。他的繪畫方法從未被調用過。 – 2010-01-25 19:27:47

+1

答案顯然是錯誤的:JFrame!是一個JComponent並且沒有paintComponent。雖然您可以實施該方法,但在正常繪畫過程中從未調用該方法。沒有原來的優勢;-) – kleopatra 2011-03-31 14:06:30

+0

@ kleopatra。絕對正確的是你。我已經改進了答案以反映你的觀點。 – 2011-03-31 14:21:05

1

幾個項目浮現在腦海中:

  1. 永不覆蓋paint()方法,這樣做的paintComponent(),而不是
  2. 你爲什麼在JFrame直接在畫什麼?爲什麼不擴展JComponent(或JPanel)並用它來代替?它提供了更大的靈活性
  3. JLabel的目的是什麼?如果它位於JFrame的頂部並覆蓋整個東西,那麼您的繪畫將隱藏在標籤後面。
  4. 繪畫代碼不應該依賴paint()中傳遞的x,y值來確定繪圖例程的起始點。 paint()用於繪製組件的一部分。在畫布上畫出你想要的橢圓。

另外,您沒有看到JLabel,因爲paint()方法負責繪製組件本身以及子組件。重寫paint()方法是邪惡=)

0

要覆蓋了錯誤的paint()方法,你應該重寫名爲的paintComponent這樣的方法:

@Override 
public void paintComponent(Graphics g) 
+1

這是爲什麼upvoted? JFrame不是JComponent,因此沒有paintComponent。 – csvan 2014-01-30 15:33:41

0

你需要重寫一個現實的繪圖方法,它實際上是爲你的框架定日期。在你的情況下,你只是創建了不被Frame默認調用的自定義新方法。

所以你的方法改成這樣:

public void paint(Graphics g){ 

}