2
我有一個程序,我在點擊創建一個JLabel,然後將其拖動到界面的另一部分。一鍵點擊並拖動?
我想要的是在JPanel中的某個地方點擊,讓它在那裏放一個JLabel,然後在同一個點擊中拖動另一個JLabel。
我可以做到這一點,但它需要多次點擊。我可以一鍵完成嗎?
爲了說明我的意思,我創造了這個示例程序:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DragTest extends JFrame implements MouseMotionListener,
MouseListener {
private JPanel panel = new JPanel(null);
private JLabel dragLabel = new JLabel("drag");;
private final JWindow window = new JWindow();
public DragTest() {
this.add(panel);
panel.addMouseListener(this);
dragLabel.setFont(new Font("Serif", Font.BOLD, 48));
}
@Override
public void mouseDragged(MouseEvent me) {
dragLabel = new JLabel("drag");
dragLabel.setFont(new Font("Serif", Font.BOLD, 48));
int x = me.getPoint().x;
int y = me.getPoint().y;
window.add(dragLabel);
window.pack();
Point pt = new Point(x, y);
Component c = (Component) me.getSource();
SwingUtilities.convertPointToScreen(pt, c);
window.setLocation(pt);
window.setVisible(true);
repaint();
}
@Override
public void mouseMoved(MouseEvent e) {
}
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
JLabel dropLabel = new JLabel("drop");
panel.add(dropLabel);
dropLabel.setForeground(Color.RED);
dropLabel.setFont(new Font("Serif", Font.BOLD, 48));
dropLabel.setBounds(e.getX(), e.getY(), 100, 60);
dropLabel.addMouseMotionListener(this);
dropLabel.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
dragLabel.setVisible(false);
window.setVisible(false);
}
});
repaint();
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
public static void main(String[] args) {
DragTest frame = new DragTest();
frame.setVisible(true);
frame.setSize(600, 400);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
因此,最初的點擊創建了「滴」的JLabel,然後單擊並拖動「滴」的JLabel將創建一個「拖動「遵循鼠標左右的JLabel。
我該如何做到這一點點擊並拖動?