所以我想單擊並拖動一個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