【问题标题】:Why doesn't this JComponent paints correctly?为什么这个 JComponent 不能正确绘制?
【发布时间】:2012-06-24 00:41:27
【问题描述】:

如果移动和调整大小,以下组件会正确绘制,但如果从屏幕外拖出则不会。

为什么?

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);
}
}

【问题讨论】:

  • “拖出屏幕”是什么意思?我无法用您的代码重现您的问题。

标签: java swing graphics awt paintcomponent


【解决方案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.setTransform 的 JavaDoc:警告:此方法绝不能用于在现有变换之上应用新的坐标变换,因为 Graphics2D 可能已经具有其他用途所需的变换,例如渲染 Swing 组件或应用缩放变换来调整打印机的分辨率。

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

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

【讨论】:

    【解决方案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());
    }
    

    【讨论】:

    • 没有帮助。效果是一样的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-15
    • 1970-01-01
    • 2016-07-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多