如何使用QuadCurve2D.Double绘制曲线段?

时间:2012-10-29 00:24:57

标签: java swing graphics2d paintcomponent

以下是我声明曲线的代码行:

QuadCurve2D.Double curve = new QuadCurve2D.Double(50,100,100,170,150,100);

现在我可以用什么代码绘制这条曲线?我试过像:

g.draw(curve);

但显然这不起作用。有什么建议吗?

2 个答案:

答案 0 :(得分:4)

我已经做了一个我认为你在这里描述的最小测试用例。 这个程序有效但除非我能看到你正在使用的代码,否则我无法真正帮助你。

import java.awt.geom.*;
import java.awt.*;
import javax.swing.*;

public class CurveDraw extends JFrame {
        public static void main(String[] args) {
                CurveDraw frame = new CurveDraw();
                frame.setVisible(true);
        }
        public CurveDraw() {
                setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                setSize(400,400);
        }
        public void paint(Graphics g) {
                QuadCurve2D.Double curve = new QuadCurve2D.Double(50,100,100,170,150,100);
                ((Graphics2D)g).draw(curve);
        }
}

答案 1 :(得分:4)

对我来说很好......

enter image description here

public class PaintQuad {

    public static void main(String[] args) {
        new PaintQuad();
    }

    public PaintQuad() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException ex) {
                } catch (InstantiationException ex) {
                } catch (IllegalAccessException ex) {
                } catch (UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new PaintMyQuad());
                frame.setSize(200, 200);
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class PaintMyQuad extends JPanel {

        @Override
        protected void paintComponent(Graphics g) {

            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();

            QuadCurve2D.Double curve = new QuadCurve2D.Double(50,100,100,170,150,100);

            g2d.setColor(Color.RED);
            g2d.draw(curve);

        }

    }

}

有两件事情浮现在脑海中。

  1. 确保您已设置图形的颜色,默认为窗格的背景颜色
  2. 确保容器的大小足够大(并且布局正确)以显示图形。