绘图问题

时间:2011-04-10 17:31:23

标签: java graphics applet drawing

现在,以下代码应该在黑色Canvas上绘制一个onMouseDragged圆圈。 不幸的是它没有(= 我想念一下吗?

提前致谢...

import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.applet.*;
import java.awt.Graphics.*;



public class IdrawApplet extends Applet  {  


    int mosX;
    int mosY;
    Panel pGadgets;
    Canvas myCanvas;
    Label lRed;
    TextField tfRed;
    TextField tfGreen;
    TextField tfBlue;
    Label lGreen;
    Label lBlue;

    Graphics g;

  public void init() {

    g = getGraphics();
    lRed = new Label("Red-value: ");
    lBlue = new Label("Blue-value: ");
    lGreen = new Label("Green-value: ");
    tfRed = new TextField();
    tfRed.setText("255");
    tfGreen = new TextField();
    tfGreen.setText("255");
    tfBlue = new TextField();
    tfBlue.setText("255");

    pGadgets = new Panel();
    pGadgets.setLayout(new GridLayout(1, 6, 5, 5));
    add(pGadgets);
    pGadgets.add(lRed);
    pGadgets.add(tfRed);
    pGadgets.add(lGreen);
    pGadgets.add(tfGreen);
    pGadgets.add(lBlue);
    pGadgets.add(tfBlue);

    myCanvas = new Canvas();
    myCanvas.setBackground(new Color(0,0,0));
    myCanvas.setBounds(0, 0, 600, 400);

    add(myCanvas);
    myCanvas.addMouseMotionListener(new MouseMotionListener() {

        public void mouseMoved(MouseEvent e) {
            // TODO Auto-generated method stub

        }

        public void mouseDragged(MouseEvent e) {
            // TODO Auto-generated method stub
            paint(g);

        }
    });


  }

  public void paint(Graphics g) {
      g.setColor(Color.green);
      g.fillOval(mosX, mosY, 30, 30);

      }





}

2 个答案:

答案 0 :(得分:4)

两件事:

public void mouseDragged(MouseEvent e) 
{
   mosX = e.getX();
   mosY = e.getY();
   repaint(); //NOT paint(g);
}

//...
public void paint(Graphics g) 
{
    //draw on the canvas not on the component 
    //since the canvas gets drawn over it
    Graphics g2 = myCanvas.getGraphics();
    g2.setColor(Color.green);
    g2.fillOval(mosX, mosY, 30, 30);
}

如果你有更复杂的东西,你应该继承Canvas并覆盖它的paint()方法。

答案 1 :(得分:1)

试试这个:

public void mouseDragged(MouseEvent e) 
{
    mosX = e.getX();
    mosY = e.getY();

    repaint();
}

问题是您没有更新mouseDragged事件的坐标。此外,您应该致电paint(),而不是直接致电repaint()。致电repaint()将确保自动调用paint()

编辑:

要在Canvas对象上绘制,请覆盖paint()对象的Canvas

myCanvas = new Canvas()
{
    public void paint(Graphics g) 
    {
        g.setColor(Color.green);
        g.fillOval(mosX, mosY, 30, 30);
    }    
};

现在你的mouseDragged方法变为:

public void mouseDragged(MouseEvent e) 
{
    mosX = e.getX();
    mosY = e.getY();

    myCanvas.repaint();
}