2012-06-21 58 views
0

如果移動和調整大小,下列組件將正確繪製,但如果從屏幕中拖出,則不會正確繪製。這個JComponent爲什麼不能正確繪製?

爲什麼?

public class Test_ShapeDraw { 
public static class JShape extends JComponent { 

    private Shape shape; 
    private AffineTransform tx; 
    private Rectangle2D bounds; 

    public JShape() { 
    } 

    public void setShape(Shape value) { 
     this.shape = value; 
     bounds = shape.getBounds2D(); 
     setPreferredSize(new Dimension((int) bounds.getWidth(), (int)bounds.getHeight())); 
     tx = AffineTransform.getTranslateInstance(-bounds.getMinX(), -bounds.getMinY()); 

    } 

    public Shape getShape() { 
     return shape; 
    } 


    @Override 
    protected void paintComponent(Graphics g) { 
     super.paintComponent(g); 

     if(shape != null) { 
      Graphics2D g2d = (Graphics2D)g; 
      g2d.setTransform(tx); 
      g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); 
      ((Graphics2D)g).draw(shape); 
     } 

    } 




} 


public static void main(String[] args) { 
    SwingUtilities.invokeLater(new Runnable() { 
     @Override 
     public void run() { 
      createAndShowGUI(); 
     } 
    }); 
} 


private static void createAndShowGUI() { 

    Shape shape = new Ellipse2D.Double(0,0,300,300); 

    JShape jShape = new JShape(); 
    jShape.setShape(shape); 

    JFrame f = new JFrame("Shape Test"); 
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    f.add(jShape); 
    f.pack(); 
    f.setVisible(true); 
} 
} 

This is what it draws if dragged from out of the left screen edge

+0

你是什麼意思「拖出屏幕」?我無法用您的代碼重現您的問題。 –

回答

4
  AffineTransform originalTransform = g2d.getTransform(); 
      g2d.transform(tx); 

      g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); 
      ((Graphics2D)g).draw(shape); 

      g2d.setTransform(originalTransform); 

說明:參見Graphics2D.setTransform的JavaDoc :警告:永遠不要使用此方法在現有轉換之上應用新的座標轉換,因爲Graphics2D可能已經具有轉換需要用於其他目的,比如渲染Swing組件或應用縮放轉換來調整打印機的分辨率。

要添加座標變換,請使用變換,旋轉,縮放或剪切方法。 setTransform方法僅用於在渲染後恢復原始的Graphics2D變換。

http://docs.oracle.com/javase/6/docs/api/java/awt/Graphics2D.html#setTransform%28java.awt.geom.AffineTransform%29

0

儘量去除的getPreferredSize()方法和在setShape方法使用了setPreferredSize():

public void setShape(Shape value) { 
    this.shape = value; 
    bounds = shape.getBounds2D(); 
    setPreferredSize(new Dimension((int) bounds.getWidth(), (int)bounds.getHeight())); 
    tx = AffineTransform.getTranslateInstance(-bounds.getMinX(), -bounds.getMinY()); 
} 
+0

沒有幫助。效果是一樣的。 –

相關問題