2012-04-08 94 views
1

沒有使用super.paintComponent(g);我仍然可以清除我的Jpanel或Jframe屏幕嗎?我在JPanel上繪製了一些圖形,並且我想要在用戶按下右鍵單擊而不使用此方法時清除所有繪圖。或者我說有super.paintCompenent(g)的任何替代;方法或方法像clrscr();在Java中。清除JPanel或JFrame

編輯

public void mousePressed(MouseEvent e) { 
      super.paintComponents(null); //i want to use this method here?? how can i? 
      if(e.isPopupTrigger()) 
      { 
       s=e.getX(); 
       as=e.getY(); 
       try { 
        Thread.sleep(10L); 
       } catch (InterruptedException ex) { 
        Logger.getLogger(animate.class.getName()).log(Level.SEVERE, null, ex); 
       } 
     p.repaint(); 
      } 
     } 

我畫這樣

public class mypanel extends JPanel { 

    @Override 
    public void paintComponent(Graphics g) 
    { 

     super.paintComponent(g); 
     Graphics2D g2=(Graphics2D)g ; 

     Color[] c = {Color.BLUE, Color.RED, Color.GREEN, Color.YELLOW, 
       Color.MAGENTA, Color.WHITE, Color.ORANGE, Color.PINK}; 
    for(int i=0; i<8; ++i){ 
     g2.setColor(c[i]); 
     int start_angle=i*45; 
    g2.fillArc(mx-100, my-100, 200, 200, start_angle,45); 



    } 
+0

後拉伸或不在您的JPanel simlpy你的代碼。 – Jeffrey 2012-04-08 16:47:23

+0

您可以調用repaint並停止調用Graphics基元。如果你有組件,那麼只需調用removeAll() – 2012-04-08 16:49:35

+0

@Jeffrey代碼是什麼?它太長。 – james 2012-04-08 16:49:59

回答

6

mre解決方案實際上是一個好主意,但是如果重新進行另一次重繪,您可能會遇到問題(因爲您移動JFrame,因爲調整了它,因爲另一個窗口位於頂部,然後放開,等等......) )

或者,也可以有這樣的事情,以使更改永久:

public class mypanel extends JPanel { 

    private boolean draw = true; 

    @Override 
    public void paintComponent(Graphics g) 
    { 

     super.paintComponent(g); 
     if (draw) { 
      Graphics2D g2=(Graphics2D)g ; 

      Color[] c = {Color.BLUE, Color.RED, Color.GREEN, Color.YELLOW, 
        Color.MAGENTA, Color.WHITE, Color.ORANGE, Color.PINK}; 
      for(int i=0; i<8; ++i){ 
       g2.setColor(c[i]); 
      int start_angle=i*45; 
      g2.fillArc(mx-100, my-100, 200, 200, start_angle,45); 
     } 
    } 

    public void setDraw(boolean draw) { 
     this.draw = draw; 
     repaint(); 
    } 
} 

然後你可以通過調用mypanel.setDraw(布爾)

+0

你是否錯過了'if(draw)'後的'{}':-),這正是我想到的+1 :-)好的答案:-) – 2012-04-08 17:18:18

+0

@nIcEcOw y,我確實。我只是修復它。 – 2012-04-08 17:20:42

4

也許Graphics#clearRect是你在找什麼形狀?

+1

+1,我會與這個答案一起去。在OP中,只需在'mousePressed(...)'的某個地方放置一個布爾變量,並通過在'paintComponent(...)'方法內檢查它來完成你在回答中所說的內容,否則像往常一樣進行正常繪圖:-) – 2012-04-08 17:11:17