2015-09-06 139 views
1

这是我的代码。它用于绘制一个圆,但我现在正在绘制一个三角形时出现问题..使用鼠标单击时会出现一个三角形,但在运行该应用程序后立即显示一个三角形。请帮忙。谢谢。在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) { 

    } 
}`` 

回答

0

您遇到的问题是您重写paint方法,因此drawPolygon方法已在JFrame的初始绘制中调用。

对于你想拥有你应该避免重写paint方法,只影响使用drawPolygon方法调用的MouseListener时。

这应该是这样的:

@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 model是什么,是设计类结构很好的一般准则。