gpt4 book ai didi

java - 使java Swing 框架可移动并设置未装饰

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:33:35 24 4
gpt4 key购买 nike

我创建了一个没有标题栏的框架,为此我使用了 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);
}
}
}

您仍然可以通过拖动框架的主体来拖动它。

关于java - 使java Swing 框架可移动并设置未装饰,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16046824/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com