繁体   English   中英

我的JComponent仅在手动调整窗口大小后才会重绘(),如何使其正常工作?

[英]My JComponent will only repaint() once I manually resize the window, how do I get it to work as it should?

我已尽力阅读有关该主题的内容,但是我找不到/不了解如何将答案应用于我的片段代码(而我所应用的答案无效)

我使用了“ 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}

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

提前致谢。

您需要致电

super.paint(g);

CurveDrawings类的paint方法中使用JFrame超级类中已经提供的绘画功能。

注意,在Swing中使用自定义绘画的标准方法是使用基于javax.swing.JComponent自定义组件,这些组件使用并覆盖paintComponent 这种方法将利用Swing的优化绘画模型。

请参阅: 执行自定义绘画

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM