[英]How to use two paint methods in java? Or outside the basic paint method
我怎樣才能創建兩種繪畫方法? 當我試圖使用兩種塗料方法時,它們永遠不會起作用。 如果不能,我想在基本的油漆方法之外繪畫,我不知道如何。 例如:
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);
}
}
當我試圖使用兩種塗料方法時,它們永遠不會起作用。
paintComponent(...)
不是JFrame的方法。 每當您嘗試覆蓋一個方法時,您應該使用@Override
注釋,編譯器會在您嘗試覆蓋不存在的方法時告訴您。
通常,對於其他Swing組件, paint(...)
方法負責調用paintComponent(...)
方法,因此不應覆蓋paint()
方法。 請參閱:詳細了解Paint Mechanism了解更多信息。
無論如何,你不應該覆蓋JFrame上的paint()。 閱讀教程鏈接中有關Performing Custom Painting
的整個部分,以獲取應如何進行自定義繪制的工作示例。
我找到了一個方法。
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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.