建立可拖曳圖片的 Swing 面板,支援雙擊開啟圖片檔案、滑鼠拖曳移動圖片位置,展示事件監聽與繪圖機制。
ImagePanel。JPanel,實作滑鼠監聽與繪圖邏輯。private enum DragStatus { Ready, Dragging }
private DragStatus status = DragStatus.Ready;
private Point imagePosition = new Point(0, 0); // 當前圖片位置
private Point imageStartPosition = new Point(0, 0); // 拖曳起始圖片位置
private Point mouseStartPosition; // 拖曳起始滑鼠位置
mouseClicked 偵測 getClickCount() == 2,彈出 JFileChooser 選擇圖片,載入後 repaint()。mousePressed 記錄滑鼠與圖片起始座標,狀態切為 Dragging。mouseDragged 計算偏移量 imagePosition = imageStart + (mouseNow - mouseStart),呼叫 repaint()。mouseReleased 狀態歸 Ready。@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (image != null) {
g.drawImage(image, (int)imagePosition.getX(), (int)imagePosition.getY(), this);
}
}
public static void main(String[] args) throws Exception {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
DragingFrame frame = new DragingFrame();
frame.setSize(400, 300);
frame.setLocation(300, 300);
frame.setResizable(false);
frame.setTitle("雙擊打開圖片,然後拖曳");
frame.setVisible(true);
}