1. paint(Graphics g)
java繪圖時,最常使用到的就是paint(Graphics g){...內容...}方法獲取畫筆,然后利用JPanel等容器作為畫布,在JFrame內呈現出內容,很多情況下這種方式都還是很實用,下附實例:
import java.awt.Color; import java.awt.Graphics; import javax.swing.JFrame; import javax.swing.JPanel; public class Test //Test為自定義的主類名,一般大寫 { public static void main(String args[]) { JFrame newFrame=new JFrame("funBox"); newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //定義JFrame關閉時的操作(必需),有效避免不能關閉后台當前框體進程的問題 newFrame.setSize(400, 400); //定義JFrame的相關屬性 newFrame.setLocation(200, 200); newFrame.setVisible(true); newFrame.add(new FangKuai()); //將需要呈現的圖像添加進JFrame中 } } class FangKuai extends JPanel //FangKuai 為自定義新建類名 { public void paint(Graphics g) //重寫實現panit()方法 { g.setColor(Color.green); //(0,0)位置繪制一個20*20的綠色方塊 g.fillRect(0, 0, 20, 20); } }
2. Graphics g=getGraphics()
有的時候,需要Graphics對象進行更多的操作(例如下面需要在run()中調用Graphics對象)而不能使用paint(Graphics g)方法,這個時候,就得獲取自己定義的Graphics對象來完成需求,下附實例
import java.applet.Applet; import java.awt.Color; import java.awt.Graphics; import javax.swing.JFrame; import javax.swing.JPanel; //以下為一個框體小程序 public class _001// _001為自定義的主類名 { public static void main(String[] args) { JFrame newFrame=new JFrame("funBox"); newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //定義JFrame關閉時的操作(必需),有效避免不能關閉后台當前框體進程的問題 newFrame.setSize(400, 400); //定義JFrame的相關屬性 newFrame.setLocation(200, 200); newFrame.setVisible(true); newThread n1= new newThread(); //線程的運行,將需要呈現的圖像添加進JFrame中 newFrame.add(n1); Thread t1 = new Thread(n1); t1.start(); } } class newThread extends JPanel implements Runnable //Java類中只能繼承一個類,但是可以實現多個接口,此處newThread 為自定義新建類名 { Graphics g; //此處定義Graphics對象 g; private static final long serialVersionUID = 1L; public void run() //進程run()方法重寫 { g=getGraphics(); //Graphics對象 g的獲取 for(int i=0;i<100;) { try { Thread.sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } this.update(g) ; //update()方法的調用,刷新圖像,使得圖像不會重疊顯現 g.setColor(Color.green); //繪制(0,0)開始移動的20*20綠色小塊 g.fillRect(i, i, 20, 20); i+=20; } } }
3. 總結
簡單的調用repaint()方法確實可以完成很多java繪圖需求,但是當需要靈活得到Graphics對象時,就必須用getGraphics()獲取了,自己Java繪圖的一點小小經驗,希望得到更多點評得以改進。