預設的,Frame或JFrame本身已經實作了滑鼠拖曳標題列移動視窗的功能。
只是,當你不滿意java的JFrame樣式,隱藏了標題列和邊框,又或者乾脆直接使用JWindow,那你又該怎麼實現滑鼠拖曳移動視窗的目的呢?最開始,我簡單的在mouseDragged方法裡frame.setLocation(e.getX(), e.getY()),結果,frame拖曳的時候不停地閃爍,位置在屏幕上不斷跳動。後來網上查資料,找到了答案。
這裡給一個簡單的範例,一看就明白:
package com.jebysun.test.globalhotkey; import java.awt.Color; import java.awt.Cursor; import java.awt.Point; import java.awt.event.MouseEvent; import javax.swing.JLabel; imwingport javax.s .JWindow; import javax.swing.event.MouseInputListener; /** * 自訂程式窗口,滑鼠可拖曳移動其位置。 * @author Jeby Sun * */ public class MyFrame extends JWindow { private static final long serialVersionUID = 1L; JLabel titleLbl; public MyFrame() { //設定背景顏色不能直接呼叫其setBackground方法,而要設定其ContententPane的背景顏色。 this.getContentPane().setBackground(new Color(0x99FF66)); this.setBounds(100,100,600,400); this.setLayout(null); titleLbl = new JLabel(" 自訂視窗標題列"bltledLqueLque); titleLbl.setBackground(new Color(0x66CC00)); titleLbl.setBounds(0, 0, 600, 30); this.add(titleLbl); //滑鼠事件處理類別MouseEventListener mouseListener = new MouseEventListener(this); 滑鼠事件處理類別MouseEventListener mouseListener = new MouseEventListener(this); 滑鼠事件處理類別MouseEventListener mouseListener = new MouseEventListener(this); 滑鼠事件處理類別MouseEventListener mouseListener = new MouseEventListener(this); 滑鼠字詞Lbl.addMouseList(motleList); addMouseMotionListener(mouseListener); this.setVisible(true); } /** * 滑鼠事件處理* @author Jeby Sun * */ class MouseEventListener implements MouseInputListener { Point origin; //滑鼠拖曳想要移動的目標元件MyFrame frame; public MouseListener(MyFrame EventameList ) { this.frame = frame; origin = new Point(); } @Override public void mouseClicked(MouseEvent e) {} /** * 記錄滑鼠按下時的點*/ @Override public void mousePressed(MouseEvent e) { origin.x = e.getX(); origin.y = e.getY(); } @Override public void mouseReleased(MouseEvent e) {} /** * 當滑鼠移轉標題列時,設定滑鼠圖示為移動圖示*/ @Override public void mouseEntered(MouseEvent e) { this.frame.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR)); } /** * 滑鼠移出標題列時,設定滑鼠圖示為預設指標*/ @Override publicited mouse (MouseEvent e) { this.frame.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } /** * 滑鼠在標題欄拖曳時,設定視窗的座標位置* 視窗新的座標位置= 移動前座標位置+(滑鼠指標目前座標-滑鼠按下時指標的位置) */ @Override public void mouseDragged(MouseEvent e) { Point p = this.frame.getLocation(); this.frame.setLocation( px + (e.getX() - origin.x), py + (e.getY() - origin.y)); } @Override public void mouseMoved( MouseEvent e) {} } public static void main(String[] args) { new MyFrame(); } }