看看這個例子。你首先需要實現mousePresseded
然後mouseDragged
。第一個獲得初始印刷的點,那麼mouseDragged
將使用這些座標。
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
// Get x,y and store them
pX = me.getX();
pY = me.getY();
}
});
addMouseMotionListener(new MouseAdapter() {
public void mouseDragged(MouseEvent me) {
frame.setLocation(frame.getLocation().x + me.getX() - pX,
frame.getLocation().y + me.getY() - pY);
}
});
完整的運行示例。它使用undecorate框架並創建一個JPanel
作爲標題,您可以通過拖動來移動框架。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.LineBorder;
public class UndecoratedExample {
static JFrame frame = new JFrame();
static class MainPanel extends JPanel {
public MainPanel() {
setBackground(Color.gray);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
}
static class BorderPanel extends JPanel {
JLabel stackLabel;
int pX, pY;
public BorderPanel() {
ImageIcon icon = new ImageIcon(getClass().getResource(
"/resources/stackoverflow1.png"));
stackLabel = new JLabel();
stackLabel.setIcon(icon);
setBackground(Color.black);
setLayout(new FlowLayout(FlowLayout.RIGHT));
add(stackLabel);
stackLabel.addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent e) {
System.exit(0);
}
});
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
// Get x,y and store them
pX = me.getX();
pY = me.getY();
}
});
addMouseMotionListener(new MouseAdapter() {
public void mouseDragged(MouseEvent me) {
frame.setLocation(frame.getLocation().x + me.getX() - pX,
frame.getLocation().y + me.getY() - pY);
}
});
}
}
static class OutsidePanel extends JPanel {
public OutsidePanel() {
setLayout(new BorderLayout());
add(new MainPanel(), BorderLayout.CENTER);
add(new BorderPanel(), BorderLayout.PAGE_START);
setBorder(new LineBorder(Color.BLACK, 5));
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
frame.setUndecorated(true);
frame.add(new OutsidePanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
參見[如何寫一個'MouseMotionListener'](http://docs.oracle.com/javase/tutorial/uiswing/events/mousemotionlistener.html) –
在run()方法執行多長時間?添加一個println()來查看。 – NormR