Can't paint on directly on JFrame

会有一股神秘感。 提交于 2019-12-11 19:06:48

问题


I have an assignment to create a paint program in Java. I have managed to create something but not exactly what I wanted.

My problem is that I cannot create a JFrame in my IDE(NetBeans 7.0.1) from the options that the IDE gives me, and call the paint classes correctly.

To be more specific I want to press a button from one panel(ex. Panel1) and paint in Panel2,in the same frame.

That's the calling of the class:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         

    PaintFlower102 f = new PaintFlower102();
}

Part of Class:

    super("Drag to Paint");
    getContentPane().add(new Label ("Click and Drag"),BorderLayout.SOUTH);
    // add(new JButton("Brush 20"),BorderLayout.NORTH);
    addMouseMotionListener( new MouseMotionAdapter() {

        @Override
        public void mouseDragged(MouseEvent event) {
            xval=event.getX();
            yval=event.getY();
            repaint();
        }
    });

    setSize(500, 500);
    setVisible(true);
    setDefaultCloseOperation(PaintFlower102.DISPOSE_ON_CLOSE);
}

public void paint(Graphics g) {      
    g.fillOval(xval, yval, 10, 10);   
}

The problem is that if I do not put the extend JFrame in the class this doesn't work. And if I do, it creates a new frame in which I can draw.


回答1:


Suggestions:

  • Don't ever paint directly in a JFrame except under rare circumstances of absolute need (this isn't one of them).
  • Instead paint in a JPanel or JComponent or other derivative of JComponent.
  • Paint in the class's paintComponent(Graphics g) method, not in paint(Graphics g).
  • Read the Java tutorials on this as it's all explained well there. Check out Trail: 2D Graphics and Performing Custom Painting.



回答2:


I might be wrong, but I think that you need to include super.paintComponent(g), and override the paintComponent method like Hovercraft Full Of Eels said.

public void paintComponent(Graphics g) {
    super.paintComponent(g);       

    // Draw Oval
   g.fillOval(xval, yval, 10, 10);
}  


来源:https://stackoverflow.com/questions/10301380/cant-paint-on-directly-on-jframe

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!