mousePressed对JPanel没有回应

时间:2018-04-30 21:14:30

标签: java swing jpanel mouseevent mouselistener

我正在尝试编写一个代码,当用户点击一次时,会出现一个小点,从第一次和第二次点击开始两次形成一行,第三次在所有点击中形成一个三角形,然后再次点击重新开始一个点。目前我可以打开我的JFrame和JPanel,但点击什么都不做。我添加了一个System.out.print命令,只是为了看看我的mousePressed方法是否曾经运行过,但它从来没有。这是我目前的代码:

import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class TriangleClicker extends JFrame {
    private final int width = 700;
    private final int height = 800;
    private JPanel panel;
    private MouseListener listener;
    private int p1x;
    private int p1y;
    private int p2x;
    private int p2y;
    private int p3x;
    private int p3y;
    private int count = 0;
    private Graphics g;

public TriangleClicker() {
    this.setSize(width, height);
    this.add(createPanel());
    listener = new MousePressListener();
}

public JPanel createPanel() {
    panel = new JPanel();
    panel.setSize(width, height);
    return panel;
}

class MousePressListener extends JComponent implements MouseListener  {
    public void drawLine1(Graphics g) {
        g.drawLine(p1x, p1y, p1x, p1y);
    }

    public void drawLine2(Graphics g) {
        g.drawLine(p1x, p1y, p2x, p2y);
    }

    public void drawLine3(Graphics g) {
        g.drawLine(p3x, p3y, p1x, p1y);
        g.drawLine(p3x, p3y, p2x, p2y);
    }
    @Override
    public void mouseClicked(MouseEvent e) {
    }
    @Override
    public void mouseEntered(MouseEvent e) {
    }
    @Override
    public void mouseExited(MouseEvent e) {
    }
    public void mousePressed(MouseEvent e) {
        if (count == 0) {
            p1x = e.getX();
            p1y = e.getY();
            drawLine1(g);
            count++;
            System.out.println("1");
        }
        else if (count == 1) {
            p2x = e.getX();
            p2y = e.getY();
            drawLine2(g);
            count++;
        }
        else if(count == 2) {
            p3x = e.getX();
            p3y = e.getY();
            drawLine3(g);
            count++;
        }
        else if(count == 4) {
            g.clearRect(0, 0, WIDTH, HEIGHT);
            p1x = e.getX();
            p1y = e.getY();
            p2x = 0;
            p2y = 0;
            p3x = 0;
            p3y = 0;
            drawLine1(g);
            count = 1;
        }
    }
    @Override
    public void mouseReleased(MouseEvent e) {
    }
}
}

非常感谢任何帮助。感谢。

0 个答案:

没有答案