使一个java swing框架可移动和setUndecorated [英] Making a java swing frame movable and setUndecorated
本文介绍了使一个java swing框架可移动和setUndecorated的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建了一个没有标题栏的框架,因为我使用了setUndecorated(true);方法但之后由于某种原因框架变得不可移动。
I have created a frame without the title bar, for that I used the setUndecorated(true); method but after that the frame is became unmovable for some reason.
如何让我的框架移动并仍隐藏我的标题栏?
How can I make my frame movable and still hide my title bar?
推荐答案
以下代码将创建一个没有标题栏的JFrame,您仍然可以移动:
The following code will create a JFrame without a title bar, which you can still move around:
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);
}
}
}
你仍然可以拖动它通过拖动框架的主体。
You can still drag it around by dragging the body of the frame.
这篇关于使一个java swing框架可移动和setUndecorated的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文