我创建了一个没有标题栏的框架,为此我使用了 setUndecorated(true); 方法,但之后框架由于某种原因变得不可移动。
我怎样才能使我的框架可移动并仍然隐藏我的标题栏?
以下代码将创建一个没有标题栏的 JFrame,您仍然可以移动它:
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class FrameDragListenerExample {
public static void main(String[] args) {
Runnable runnable = new Runnable() {
public void run() {
final JFrame frame = new JFrame("Hello");
frame.setUndecorated(true);
frame.setBounds(0, 0, 400, 400);
JPanel contentPane = new JPanel(new BorderLayout());
JLabel label = new JLabel("Click anywhere in the Jframe and drag");
label.setFont(label.getFont().deriveFont(16f));
label.setBorder(BorderFactory.createEmptyBorder(100, 100, 100, 100));
contentPane.add(label);
frame.setContentPane(contentPane);
FrameDragListener frameDragListener = new FrameDragListener(frame);
frame.addMouseListener(frameDragListener);
frame.addMouseMotionListener(frameDragListener);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
};
SwingUtilities.invokeLater(runnable);
}
public static class FrameDragListener extends MouseAdapter {
private final JFrame frame;
private Point mouseDownCompCoords = null;
public FrameDragListener(JFrame frame) {
this.frame = frame;
}
public void mouseReleased(MouseEvent e) {
mouseDownCompCoords = null;
}
public void mousePressed(MouseEvent e) {
mouseDownCompCoords = e.getPoint();
}
public void mouseDragged(MouseEvent e) {
Point currCoords = e.getLocationOnScreen();
frame.setLocation(currCoords.x - mouseDownCompCoords.x, currCoords.y - mouseDownCompCoords.y);
}
}
}
您仍然可以通过拖动框架的主体来拖动它。
也许这会帮助你 移动窗口
我为你封装了一个扩展JFrame
类,我称之为MoveaFrame
,你只需要在实践中“扩展MoveaFrame”即可:
只需将以下代码复制到您的项目中,并扩展它,您就可以使您的 Frame 窗口可拖动!
MoveJFrame
像 extend a 一样扩展,JFrame
你可以直接拖动你的窗口:
public class ContactUi extends MoveJFrame implements Runnable {
类MoveJFrame
代码,只需复制它并像 extend 一样扩展它JFrame
:
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
public class MoveJFrame extends JFrame {
public MoveJFrame() {
this.setUndecorated(true);
FrameDragListener frameDragListener = new FrameDragListener(this);
this.addMouseListener(frameDragListener);
this.addMouseMotionListener(frameDragListener);
this.pack();
this.setLocationRelativeTo(null);
this.setVisible(true);
}
public static void main(String[] args) throws IOException {
new MoveJFrame();
}
public static class FrameDragListener extends MouseAdapter {
private final JFrame frame;
private Point mouseDownCompCoords = null;
public FrameDragListener(JFrame frame) {
this.frame = frame;
}
public void mouseReleased(MouseEvent e) {
mouseDownCompCoords = null;
}
public void mousePressed(MouseEvent e) {
mouseDownCompCoords = e.getPoint();
}
public void mouseDragged(MouseEvent e) {
Point currCoords = e.getLocationOnScreen();
frame.setLocation(currCoords.x - mouseDownCompCoords.x, currCoords.y - mouseDownCompCoords.y);
}
}
}