在java图形中使用鼠标单击绘制三角形



这是我的代码。它可以画一个圆,但我现在画一个三角形有麻烦…使用鼠标点击应该出现一个三角形,但它在运行应用程序后立即显示一个三角形。请帮助。谢谢。

    package mouse;
import java.awt.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.event.*;
import java.awt.geom.*;
public class triangle extends JFrame implements ActionListener, MouseListener {
    int xx[]= {20, 50, 80};
    int yy[]= {80, 30, 80};

    public triangle () {
        setSize(2000,2000);
        addMouseListener(this);
    }
    public static void main(String[] args) {
        //TODO code application logic here
        java.awt.EventQueue.invokeLater(new Runnable() {
              public void run() {
                   triangle frame = new triangle();
                   frame.setVisible(true);
              }
        });
    }
    public void actionPerformed(ActionEvent ae) {
    }
    public void drawPolygon(int x, int y, int i)
    {
        Graphics g = this.getGraphics();
        g.setColor(Color.BLACK);
        g.drawPolygon(xx, yy, 3);
    }
    int x, y;
    public void mouseClicked(MouseEvent e) {
        x = e.getX();
        y = e.getY();
        repaint();
    }

    @Override
    public void paint(Graphics g) {
        drawPolygon(x, y, 3);
    }

    public void mouseExited(MouseEvent e) {
    }
    public void mousePressed(MouseEvent e) {
    }
    public void mouseReleased(MouseEvent e) {
    }
    public void mouseEntered(MouseEvent e) {
    }
}``

你的问题是你重写了paint方法,因此drawPolygon方法已经在JFrame的初始绘制中被调用了。

对于你想要的效果,你应该避免重写paint方法,只在调用MouseListener时使用drawPolygon方法。

应该是这样的:

@Override
public void mouseClicked(MouseEvent e) {
    x = e.getX();
    y = e.getY();
    drawPolygon(x,y,3);
    repaint();
}

为了绘制你用鼠标点击的三角形,你需要将当前位置添加到原始三角形坐标中,如下所示:

public void drawPolygon(int x, int y, int i)
{
    Graphics g = this.getGraphics();
    g.setColor(Color.BLACK);
    int[] drawx = {xx[0]+x,xx[1]+x,xx[2]+x};
    int[] drawy = {yy[0]+y,yy[1]+y,yy[2]+y};
    g.drawPolygon(drawx, drawy, i);
}

我希望这能回答你的问题。

关于编程的一些一般注意事项:一定要包含

               frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

否则程序不会在关闭帧时终止并继续运行。

如果您避免将所有内容放在一个类中,而将代码分成几个类,这也有助于代码的可读性。MVC模型是设计类结构的一个很好的通用指南。

最新更新