20110902

getGraphics() 回傳 NULL

要在APPLET(init階段)裡取得Jpanel的graphics時遇到return null的問題,google後發現似乎並不能隨時取得container裡componen的graphic,至少在container為不可見時後,container裡的componet都無法取得graphics,但有別的方法可以在不可見或初始階段就先寫好繪圖。
(但其實仍是在容器可見時才執行)
//失敗(JApplet init) jp.getGraphics() 為null
JPanel jp=new JPanel();
jp.getGraphics().drawString("123",20,20);

//可取得
JPanel jp=new JPanel(){
    public void paintComponent(Graphics  g){
        g.drawString("21113", 10, 200);
    }
};

//在事件中也可取得
button.addMouseListener(new   MouseAdapter(){
   public   void   mouseClicked(MouseEvent me){
      Graphics2D g2 =(Graphics2D) panel.getGraphics();
      g2.drawRect(20,20,100,300);
   }
}); 

沒有留言: