我正在嘗試使它能夠在窗口周圍點擊並拖動一個ImageIcon(在這種情況下是一張卡片圖像,但我想通常會學習如何操作),但我真的不知道如何。我希望能夠點擊並按住鼠標按鈕,拖動ImageIcon,並保持它在我釋放鼠標按鈕的位置。ImageIcon點擊並拖動窗口
這是我到目前爲止的代碼:
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class MyFirstClass
{
public static void main(String[] args)
{
//load the card image from the gif file.
final ImageIcon cardIcon = new ImageIcon("cardImages/tenClubs.gif");
JLabel lbl = new JLabel(cardIcon);
//create a panel displaying the card image
JPanel panel = new JPanel()
{
//paintComponent is called automatically by the JRE whenever
//the panel needs to be drawn or redrawn
public void paintComponent(Graphics g) {
super.paintComponent(g);
cardIcon.paintIcon(this, g, 20, 20);
}
};
lbl.setTransferHandler(null);
MouseListener listener = new MouseAdapter() {
public void mousePressed(MouseEvent me) {
JComponent comp = (JComponent) me.getSource();
TransferHandler handler = comp.getTransferHandler();
handler.exportAsDrag(comp, me, TransferHandler.COPY);
}
};
lbl.addMouseListener(listener);
//create & make visible a JFrame to contain the panel
JFrame window = new JFrame("Cards");
window.add(panel);
window.setPreferredSize(new Dimension(200,200));
window.pack();
window.setVisible(true);
}
}
謝謝。
非常感謝你! – user3281845
玩轉數據轉儲;) – MadProgrammer