2

我已尽力阅读该主题,但我无法找到/理解如何将答案应用于我的代码(并且我应用的那些代码不起作用)

我使用了“Ivor Horton 的 Java 2 JDK 入门书”中的一个示例,这是我第一次使用repaint(),但除非我调整窗口大小,否则它似乎不起作用。它尝试重新绘制但使屏幕空白。

这是代码,如果我做错了什么,请告诉我。

public class CurveDrawings extends JFrame{
public CurveDrawings (String title){
    setTitle(title);
    setDefaultCloseOperation(EXIT_ON_CLOSE);

    pane = new CurvePane();                     //Create pane containing curves
    Container content = getContentPane();       //Get the content pane

    //Add the pane containing the curves to the content pane for the applet
    content.add(pane);

    MouseHandler handler = new MouseHandler();
    pane.addMouseListener(handler);
    pane.addMouseMotionListener(handler);
}

//Class defining pane on which to draw
class CurvePane extends JComponent{
    public CurvePane(){
        quadCurve = new QuadCurve2D.Double(
            startQ.x, startQ.y, control.x, control.y, endQ.x, endQ.y
        );

        cubicCurve = new CubicCurve2D.Double(
            startC.x, startC.y, controlStart.x, controlStart.y,
            controlEnd.x, controlEnd.y, endC.x, endC.y
        );
    }
}

class Marker{//not needed for my problem}

class MouseHandler extends MouseInputAdapter{
    public void mousePressed(MouseEvent e){
        if(ctrlQuad.contains(e.getX(),e.getY())){
            selected = ctrlQuad;}
        else if(ctrlCubic1.contains(e.getX(),e.getY())){
            selected = ctrlCubic1;}
        else if(ctrlCubic2.contains(e.getX(),e.getY())){
            selected = ctrlCubic2;}
    }


    public void mouseReleased (MouseEvent e){
        selected = null;
    }

    public void mouseDragged (MouseEvent e){
        System.out.println("DRAGGED");
        if(selected != null){
            //Set the marker to current cursor position
            selected.setLocation(e.getX(),e.getY());
            pane.validate();
            pane.repaint();
        }
    }

    Marker selected = null;
}

    public void paint (Graphics g){
        Graphics2D g2D = (Graphics2D)g;         //Get a 2D device context
    //Code to draw each component
    }



//Points for quadratic curve

//Points for cubic curve

//More unnecessary code}

如果有任何帮助,这里是应用程序的“启动器”类

提前致谢。

4

1 回答 1

4

你需要打电话

super.paint(g);

在您的类中的paint方法中,CurveDrawings以利用JFrame超类中已经提供的绘画功能。

请注意,在 Swing 中使用自定义绘制的标准方法是使用基于javax.swing.JComponent该 use 和 override的自定义组件paintComponent。这种方法将利用 Swing 的优化绘画模型。

请参阅:执行自定义绘画

于 2012-10-27T17:03:16.200 回答