2014-09-13 34 views
3

我如何創建兩種油漆方法? 當我試圖使用他們的兩個繪畫方法是從來沒有工作。 如果不能,我想在基本的油漆方法之外油漆,我不知道如何。 例如:如何在java中使用兩種繪畫方法?或者在基本的油漆方法之外

public class test extends JFrame { 

private JPanel contentPane; 

/** 
* Launch the application. 
*/ 
public static void main(String[] args) { 
    EventQueue.invokeLater(new Runnable() { 
     public void run() { 
      try { 
       test frame = new test(); 
       frame.setVisible(true); 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } 
    }); 
} 

public void paint(Graphics g) { 
    g.fillRect(100, 100, 100, 100); 
} 

public void pp(Graphics g) { 
    g.fillRect(250, 100, 100, 100); 
} 

/** 
* Create the frame. 
*/ 
public test() { 
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    setBounds(100, 100, 450, 300); 
    contentPane = new JPanel(); 
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); 
    contentPane.setLayout(new BorderLayout(0, 0)); 
    setContentPane(contentPane); 
} 

} 
+1

這兩種方法,有不同的責任'(油漆的paintComponent)'。在我看來,首先從[執行自定義繪畫](http://docs.oracle.com/javase/tutorial/uiswing/painting/)學習繪畫的基礎知識,然後嘗試一下。不要在頂層容器上「繪製」,而是將這個任務委託給某個容器,比如「JPanel/JComponent」,並且繪製其paintComponent方法。 'paint()'將自動調用'paintComponent()'。此外,儘量不要使用'AbsolutePositiong',而是使用相關的'LayoutManager' – 2014-09-13 04:16:57

+1

這可以幫助你http://docs.oracle.com/javase/tutorial/uiswing/painting/step2.html – Jack 2014-09-13 04:17:51

+0

請*請*閱讀一個關於面向對象編程的完整指南。如果你知道方法,你將永遠不必問這個問題。 – Qix 2014-09-14 19:14:44

回答

1

我找到了一種方法。

public void paint(Graphics g) { super.paint(g); draw(g); draw2(g); }

public void draw(Graphics g){ 
    g.fillRect(100, 100, 100, 100); 
} 

public void draw2(Graphics g){ 
    g.setColor(Color.blue); 
    g.fillRect(200, 100, 100, 100); 
} 
5

當我試圖對他們的永遠不會工作使用兩種漆的方法。

paintComponent(...)不是JFrame的方法。每當你試圖覆蓋一個方法時,你都應該使用@Override註解,當你試圖覆蓋一個不存在的方法時,編譯器會告訴你。

一般來說,對於其他Swing組件,paint(...)方法負責調用paintComponent(...)方法,因此您不應該重寫paint()方法。請參閱:A Closer Look at the Paint Mechanism瞭解更多信息。

無論如何,你不應該重寫JFrame上的paint()。從教程鏈接中閱讀關於Performing Custom Painting的全部內容,以獲得自定義繪畫應該如何完成的工作示例。

相關問題