有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么这个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


共 (2) 个答案

  1. # 1 楼答案

                AffineTransform originalTransform = g2d.getTransform();
                g2d.transform(tx);
    
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                ((Graphics2D)g).draw(shape);
    
                g2d.setTransform(originalTransform);
    

    说明:有关Graphics2D,请参阅JavaDoc。setTransform:警告:决不能使用此方法在现有变换的基础上应用新的坐标变换,因为Graphics2D可能已经有了其他用途所需的变换,例如渲染Swing组件或应用缩放变换来调整打印机的分辨率

    要添加坐标变换,请使用变换、旋转、缩放或剪切方法。setTransform方法仅用于在渲染后恢复原始Graphics2D变换

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

  2. # 2 楼答案

    尝试删除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());
    }