我创建了一个没有标题栏的框架,因为我使用了setUndecorated(true);方法但之后由于某种原因,框架变得不可移动。
如何让我的框架移动并仍隐藏我的标题栏?
答案 0 :(得分:15)
以下代码将创建一个没有标题栏的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);
}
}
}
您仍然可以通过拖动框架的主体来拖动它。
答案 1 :(得分:2)
也许这会对你有用Moving Window
答案 2 :(得分:0)
我为您封装了一个扩展的JFrame
类,我将其称为MoveaFrame
,您只需在实践中“扩展MoveaFrame”即可:
只需将以下代码复制到您的项目中,然后对其进行扩展,就可以使“框架”窗口可拖动!
像扩展MoveJFrame
一样扩展JFrame
,您可以直接拖动窗口:
public class ContactUi extends MoveJFrame implements Runnable {
MoveJFrame
类代码,只需复制它并像扩展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);
}
}
}