gpt4 book ai didi

java - 点击标签时出现2次

转载 作者:行者123 更新时间:2023-11-30 03:12:32 25 4
gpt4 key购买 nike

我尝试在单击框架时进行 make,它会显示单击点的坐标。我这样做了:

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) {}

但是当我单击时,它首先显示中心的坐标,然后显示单击点,两次。但我只想要一个并且在点击点。我哪里出错了,我该怎么办?

最佳答案

只需使用mousePressed即可。单击鼠标时,通常会调用 3 个方法 - mousePressedmouseReleased,如果鼠标在按下和释放之间没有移动,则 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();
}

作为附带建议,请注意,您可以让它扩展 MouseAdapter,而不是让类实现 MouseListener,这样您的类就不必拥有所有这些空的 MouseListener 接口(interface)方法。

例如:

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();
}
});
}
}

关于java - 点击标签时出现2次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33321709/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com