我在点击框架时尝试制作,它会显示点击点的坐标。我这样做了:
public void mouseClicked(MouseEvent e) {
int x = e.getX();
int y = e.getY();
j1.setLocation(x, y);
j1.setText("(" + x + ", " + y + ")");
}
public void mousePressed(MouseEvent e) {
int x = e.getX();
int y = e.getY();
j1.setLocation(x, y);
j1.setText("(" + x + ", " + y + ")");
}
public void mouseDragged(MouseEvent e) {}
public void mouseMoved(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
但是当我点击它时,首先在中心显示坐标,然后是点击点,2次。但我只想要一个和点击点。我在哪里弄错了,我该怎么办?
答案 0 :(得分:2)
只需使用mousePressed
就可以了。当您单击鼠标时,通常会调用3种方法 - mousePressed
,mouseReleased
,如果鼠标在按下和释放之间不移动,则mouseClicked
。您只想响应其中一种方法。
所以改为:
public void mouseClicked(MouseEvent e) {} // leave this empty
public void mousePressed(MouseEvent e) {
int x = e.getX();
int y = e.getY();
j1.setLocation(x, y);
j1.setText("(" + x + ", " + y + ")");
// also be sure to tell your container to re-position components
revalidate();
repaint();
}
作为一个侧面建议,请注意,不是让一个类实现MouseListener,而是可以让它扩展MouseAdapter,这样你的类就不必拥有所有那些空的MouseListener接口方法。
例如:
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;
@SuppressWarnings("serial")
public class MousePosition extends JPanel {
private static final int PREF_W = 600;
private static final int PREF_H = PREF_W;
// format String for display String
protected static final String FORMAT = "(%d, %d)";
private int xPos = -40;
private int yPos = -40;
private String displayText = "";
public MousePosition() {
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
xPos = e.getX();
yPos = e.getY();
// use FORMAT String to create our display text
displayText = String.format(FORMAT, xPos, yPos);
repaint();
}
});
}
@Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString(displayText, xPos, yPos);
}
private static void createAndShowGui() {
MousePosition mainPanel = new MousePosition();
JFrame frame = new JFrame("MousePosition");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}