使用未装饰的 JFrame 时如何添加对调整大小的支持?

2022-01-24 00:00:00 resize customization java swing jframe

我想自定义我的标题栏、最小化、最大化和关闭按钮.所以我在我的 JFrame 上使用了 setUndecorated(true);,但我仍然希望能够调整窗口大小.实现它的最佳方法是什么?

I would like to customize my titlebar, minimize-, maximize- and the close-button. So I used setUndecorated(true); on my JFrame, but I still want to be able to resize the window. What is the best way to implement that?

我在 RootPane 上有一个边框,我可以在边框或 RootPane 上使用 MouseListeners.有什么建议吗?

I have a border on the RootPane, and I could use MouseListeners on the Border or the RootPane. Any recommendations?

import java.awt.Color;

import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.border.LineBorder;

public class UndecoratedFrame extends JFrame {

    private LineBorder border = new LineBorder(Color.BLUE,2);
    private JMenuBar menuBar = new JMenuBar();
    private JMenu menu = new JMenu("File");
    private JMenuItem item = new JMenuItem("Nothing");

    public UndecoratedFrame() {
        menu.add(item);
        menuBar.add(menu);
        this.setJMenuBar(menuBar);
        this.setUndecorated(true);
        this.getRootPane().setBorder(border);
        this.setSize(400,340);
        this.setVisible(true);
    }

    public static void main(String[] args) {
        new UndecoratedFrame();
    }
}

推荐答案

正如你所说,你的根窗格上有一个边框.因此,至少有一个位置(在绘制边框的位置下方)您的根窗格是最上面的组件.因此,您可以为其添加鼠标侦听器和鼠标运动侦听器.

As you said, you have a border on your root pane. As a consequence, there is at least one location (below the palce where your border is drawn) where your root pane is the upmost component. As a consequence, you can add it a mouse listener and a mouse motion listener.

当您的根窗格被单击(并按下鼠标按钮)时,您的鼠标和运动侦听器将通知您鼠标的初始位置和实际位置.因此,您可以更新两个值之间偏移的帧大小,使您的帧可调整大小.

When your root pane is clicked (and the mouse button is pressed), your mouse and motion listeners will inform you of the initial and actual mouse position. As a consequence, you can update your frame size of the offset between both values, making your frame resizable.

相关文章