所以我想单击并拖动一个JLabel在JFrame周围。下面的代码允许JLabel在屏幕上的任意点按下/拖动鼠标时在屏幕上移动,但我不确定如何添加第二个ActionListener来检查鼠标是否点击标签,假设是解决方案。在屏幕上拖动一个jlabel
我想在屏幕上有多个JLabel,以便唯一移动的标签是鼠标点击并拖动的标签。
谢谢。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
@SuppressWarnings("serial")
public class test extends JFrame implements MouseMotionListener {
private JPanel panel = new JPanel(null);
private JLabel dragLabel = new JLabel("drag test");
private int mouseX = 200;
private int mouseY = 200;
public test() {
this.add(panel);
panel.setBackground(Color.WHITE);
panel.add(dragLabel);
dragLabel.setForeground(Color.RED);
dragLabel.setBounds(mouseX, mouseY, 100, 50);
panel.addMouseMotionListener(this);
}
@Override
public void mouseDragged(MouseEvent e) {
mouseX = e.getX();
mouseY = e.getY();
dragLabel.setBounds(mouseX, mouseY, 100, 50);
}
@Override
public void mouseMoved(MouseEvent e) {}
public static void main(String[] args) {
test frame = new test();
frame.setVisible(true);
frame.setSize(600, 400);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
请参阅我的回答除了 – 2011-02-05 16:04:56