我正在编写一个程序,鼠标监听器mousePressed()似乎没有响应。我现在已经编写了一些GUI程序,并且比较了这些代码,我没有看到任何可以解释缺少鼠标监听的显着差异。以下代码不完整,其部分仅用于测试功能,其中一些可能没有意义。我只需要知道为什么mousePressed()不起作用。
/**This class creates a panel that draws a polygon with as many vertices as the user desires. It will have a button that tells the component to close the
polygon. Vertices are chosen with clicks of the mouse on the drawing surface.*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PolygonDraw extends JPanel implements ActionListener{
DrawPanel drawingSurface;
int[][] coordinates, oldCoordinates;
int indices = 1;
static int x = 50;
public PolygonDraw(){
//create painting panel.
setLayout(new BorderLayout());
drawingSurface = new DrawPanel();
add(drawingSurface, BorderLayout.CENTER);
JButton closePoly = new JButton("Close the Polygon");
closePoly.addActionListener(this);
JButton clear = new JButton("Clear");
clear.addActionListener(this);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(0,1));
buttonPanel.setBorder(BorderFactory.createEtchedBorder());
buttonPanel.add(clear);
buttonPanel.add(closePoly);
add(buttonPanel, BorderLayout.SOUTH);
}
private class DrawPanel extends JPanel{
public void DrawPanel(){
addMouseListener(new MouseAdapter(){
/**
This creates an array containing coordinates for every mouse press. Logic in this allows for the creation of array that get larger and larger as more
vertices are created by the user.
*/
public void mousePressed(MouseEvent evt){//compile list of vertices
//create the last element in the array.
//create an array with i elements
/*coordinates = new int[indices][2];
coordinates[indices - 1][0] = evt.getX();
coordinates[indices - 1][1] = evt.getY();
if (oldCoordinates != null){
for (int i = 0; i < indices - 1; i++){
coordinates[i][0] = oldCoordinates[i][0];
coordinates[i][1] = oldCoordinates[i][1];
}
}
oldCoordinates = coordinates;
indices++;*/
x += 5;
repaint();
}
});
}
public void paintComponent(Graphics g){//draw lines between vertices, finish polygon, and fill polygon in with a color.
//int x, y;
//super.paintComponent(g);
/*g.setColor(Color.BLACK);
for(int i = 0; i <= indices; i++){
x = coordinates[i][0];
y = coordinates[i][1];
g.fillOval(x + 2, y + 2, 4, 4);
}
*/
g.fillRect(x,50,50,50);
}
}
public void actionPerformed(ActionEvent evt){//Clear drawing area, or close vertices to make polygon.
}
}
答案 0 :(得分:3)
public void DrawPanel() {
不是有效的构造函数,它只是一种常规方法。
您应该使用更像public DrawPanel() {
的内容,这样在您创建类的新实例时将注册MouseListener
此外,请确保您正在拨打super.paintComponent
,否则您最终会遇到一堆其他问题......
@Override
protected void paintComponent(Graphics g) {//draw lines between vertices, finish polygon, and fill polygon in with a color.
super.paintComponent(g);