我只是在学习java,我有一个项目,我希望能够用鼠标在窗口周围移动JLabel。
我设置了一个名为BasicWindow1的类,实现了一个MouseMotionListener,实例化了一个JFrame容器,向JFrame添加了一个JLabel,设置了一个mouseDragged方法,将JLabel的setBounds方法连接到MouseEvent信息中,编译了它,然后运行.
但是.。
当我拖动JLabel时,它上方出现了第二个幽灵标签,并与它的虚拟兄弟一起愉快地移动着。
我已经包括了下面的代码,我希望有人会对我感兴趣,并纠正我。我猜这可能是一个简单的初学者的错误,但它使我疯狂。
在调试级别上,我在MouseEvent方法中插入了带有mouseDragged的println(e),它显示了MOUSE_DRAGGED x,y元素在两个不同的x,y路径之间振荡,一个用于幽灵,另一个用于其虚拟兄弟。
谢谢你找我,迈克
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class BasicWindow1 implements MouseMotionListener {
JFrame jf = new JFrame();
JLabel label2 = new JLabel("label2");
public BasicWindow1(String string) {
//JFrame
jf.setTitle(string);
jf.setSize(400,400);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setLayout(null);
jf.setVisible(true);
label2.setOpaque(true);
label2.setBackground(Color.cyan);
label2.setBounds(0,150,75,25);
label2.addMouseMotionListener(this);
jf.add(label2);
}//end constructor
public void mouseDragged(MouseEvent e) {
label2.setBounds(e.getX(),e.getY(),75,25);
System.out.println("e = " + e);
}
public void mouseMoved(MouseEvent e) {}
public static void main(String[] args) {
BasicWindow1 mybw = new BasicWindow1("Basic Window for Stack Overflow");
}
}发布于 2020-11-13 06:37:03
您的问题是将MouseMotionListener添加到错误的组件中。您需要将它添加到label2的父级,这是jf的内容窗格。
试试下面的代码。
import java.awt.Color;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class BasicWindow1 implements MouseMotionListener {
JFrame jf = new JFrame();
JLabel label2 = new JLabel("label2");
public BasicWindow1(String string) {
// JFrame
jf.setTitle(string);
jf.setSize(400, 400);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setLayout(null);
jf.setVisible(true);
label2.setOpaque(true);
label2.setBackground(Color.cyan);
label2.setBounds(0, 150, 75, 25);
jf.getContentPane().addMouseMotionListener(this); // CHANGE HERE
jf.add(label2);
}// end constructor
public void mouseDragged(MouseEvent e) {
label2.setLocation(e.getX(), e.getY()); // CHANGE HERE
}
public void mouseMoved(MouseEvent e) {
}
public static void main(String[] args) {
BasicWindow1 mybw = new BasicWindow1("Basic Window for Stack Overflow");
}
}方法getX()和getY(),在类MouseEvent中,返回鼠标指针在添加MOuseMotionListener的组件的坐标空间中的位置。在您的例子中,这是鼠标指针在JLabel中的位置,但这不是您想要的。您需要鼠标指针在要拖动JLabel的组件的坐标空间中的位置,其中是JFrame,或者更准确地说是JFrame的内容窗格。
有关另一种解决方案,请参阅dragging a jlabel around the screen
https://stackoverflow.com/questions/64816288
复制相似问题