1. 程式人生 > >java swing設定窗體無邊框後滑鼠還能拖動窗體的方法

java swing設定窗體無邊框後滑鼠還能拖動窗體的方法

import java.awt.EventQueue; import java.awt.Point; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionAdapter; import javax.swing.JFrame; public class P { private JFrame frame; // 全域性的位置變數,用於表示滑鼠在視窗上的位置 static Point origin = new Point(); /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { P window = new P(); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public P() { initialize(); } /** * Initialize the contents of the frame. */ private void initialize() { frame = new JFrame(); frame.setBounds(100, 100, 380, 290); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(null); frame.setLocationRelativeTo(null); frame.setUndecorated(true); frame.addMouseListener(new MouseAdapter() { // 按下(mousePressed 不是點選,而是滑鼠被按下沒有擡起) public void mousePressed(MouseEvent e) { // 當滑鼠按下的時候獲得視窗當前的位置 origin.x = e.getX(); origin.y = e.getY(); } }); frame.addMouseMotionListener(new MouseMotionAdapter() { // 拖動(mouseDragged 指的不是滑鼠在視窗中移動,而是用滑鼠拖動) public void mouseDragged(MouseEvent e) { // 當滑鼠拖動時獲取視窗當前位置 Point p = frame.getLocation(); // 設定視窗的位置 // 視窗當前的位置 + 滑鼠當前在視窗的位置 - 滑鼠按下的時候在視窗的位置 frame.setLocation(p.x + e.getX() - origin.x, p.y + e.getY()- origin.y);
} }); } }