You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何自定义实现圆角、无标题栏且无控制按钮的JDialog

自定义圆角无标题JDialog实现方案

实现需求总共需要3个核心步骤,提供两种实现方式可选:

核心前置操作

  • 调用setUndecorated(true)关闭默认窗口装饰,直接移除原生标题栏和控制按钮,注意该方法必须在setVisible(true)之前调用,否则会抛出异常
  • 取消Swing组件默认的不透明属性,避免圆角区域出现黑色背景块

方式1:直接设置窗口形状(最简单,适配JDK8+)

直接调用AWT提供的setShape方法给窗口设置固定圆角形状,代码量最少:

import javax.swing.*;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;

public class RoundedDialog extends JDialog {
    // 圆角半径,可自行调整
    private static final int CORNER_RADIUS = 20;

    public RoundedDialog(Frame parent) {
        super(parent, true);
        // 移除标题栏和控制按钮
        setUndecorated(true);
        setSize(400, 250);
        setLocationRelativeTo(parent);

        // 设置窗口圆角
        setShape(new RoundRectangle2D.Double(0, 0, getWidth(), getHeight(), CORNER_RADIUS, CORNER_RADIUS));

        // 可选:监听窗口大小变化,动态更新圆角
        addComponentListener(new ComponentAdapter() {
            @Override
            public void componentResized(ComponentEvent e) {
                setShape(new RoundRectangle2D.Double(0, 0, getWidth(), getHeight(), CORNER_RADIUS, CORNER_RADIUS));
            }
        });

        // 自定义内容区域
        JPanel content = new JPanel();
        content.setBackground(Color.WHITE);
        content.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        content.add(new JLabel("自定义圆角无标题Dialog示例"));
        setContentPane(content);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(800, 600);
            frame.setVisible(true);
            new RoundedDialog(frame).setVisible(true);
        });
    }
}

方式2:透明窗口+自定义绘制(适配更复杂样式)

如果需要添加阴影、渐变背景、自定义边框等效果,用该方式实现:

  1. 调用setBackground(new Color(0,0,0,0))将窗口背景设置为完全透明
  2. 自定义内容面板重写paintComponent方法,自行绘制圆角、阴影、背景等效果
  3. 将自定义面板设置为dialog的内容面板,面板opaque属性设为false

最终效果

预期的JDialog效果

内容的提问来源于stack exchange,提问作者o.o

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 11:57:03