我的mousepressed()函数没有被调用?

时间:2017-09-26 12:43:35

标签: java eclipse

并感谢您点击此问题。对于我的java类,我正在尝试制作一个图形,每当我在鼠标位置点击它时绘制一个点。这是我的gui窗口的代码:

import javax.swing.*;
import java.awt.*;

public class GUIWindow {

public static void main(String[] args) {
        JFrame theGUI = new JFrame();
        theGUI.setTitle("Drawing Program");
        theGUI.setSize(300, 200);
        theGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        ColorPanel panel = new ColorPanel(Color.white);
        Container pane = theGUI.getContentPane();
        pane.add(panel);
        theGUI.setVisible(true);
    }

}

这只是设置我的Gui及其尺寸。这是我的另一个类,我尝试执行mouseClick()函数:

import java.awt.*;
import java.awt.event.*;

import javax.swing.JPanel;

public class ColorPanel extends JPanel {

private int x, y;

public ColorPanel(Color backColor) {
    // TODO Auto-generated constructor stub
    setBackground(backColor);
    addMouseListener(new PanelListener()); //the mouselistener is added here
}


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

    int x = getWidth() / 2; //this just makes it so the graph lines stay centered if the window is resized.
    int y = getHeight() / 2;


    g.setColor(Color.black);  //draws graph and sets (0,0)
    g.drawLine(x, 0, x, (y * 2));
    g.drawLine(0, y, (x * 2), y);
    g.setColor(Color.red);
    g.drawOval(x-5, y-5, 10, 10);
    g.drawString("(0, 0)", x - 13, y - 10);


}

public void drawPoint(){

    Graphics g = getGraphics(); //this function uses the info taken from the mouseclick function and makes a small circle there.

    g.setColor(Color.BLUE);
    g.drawOval(x, y, 5, 5);
    g.fillOval(x, y, 5, 5);
}

private class PanelListener extends MouseAdapter{
    //mouse press class. Gets x and y, and calls the drawpoint function.

    public void mouseClicked(MouseEvent e) {
        x = e.getX();
        y = e.getY();
        System.out.println("lll"); //tester to see if the mosepress class is getting run. It doesn't.
        drawPoint();
    }

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

我可以看到的代码中没有错误,鼠标点击起来并不起作用。您看到的打印行不打印,这意味着由于某种原因,鼠标点击功能未被调用。我已经盯着这几天了,有一个朋友看一看,我们不知道发生了什么。如果你能帮助我,我会非常感激。谢谢!

0 个答案:

没有答案