Java Swing 自定义JOptionPane

运行后的样式

java 复制代码
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class demoB {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame jf = new JFrameDemo();
            jf.setVisible(true);
        });
    }

    static class JFrameDemo extends JFrame {
        private JButton button;

        public JFrameDemo() {
            setTitle("主窗口");
            setSize(400, 300);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            setLocationRelativeTo(null);

            button = new JButton("打开对话框");
            button.addActionListener(new DialogListener());
            
            getContentPane().add(button, BorderLayout.CENTER);
        }

        public JButton getJButton() {
            return button;
        }
    }

    static class DialogListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            // 主面板(设置内边距)
            JPanel mainPanel = new JPanel(new GridLayout(2, 1, 5, 10)); // 行间距10像素
            mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); // 外边距

            // 创建两行输入区域
            mainPanel.add(createInputRow("按钮1"));
            mainPanel.add(createInputRow("按钮2"));

            // 显示对话框
            JOptionPane.showOptionDialog(
                    null,
                    mainPanel,
                    "标题",
                    JOptionPane.DEFAULT_OPTION,
                    JOptionPane.PLAIN_MESSAGE,
                    null,
                    new Object[]{},  // 必须空数组
                    null
            );
        }

        // 创建单行布局(核心修改部分)
        private JPanel createInputRow(String buttonText) {
            JPanel panel = new JPanel(new BorderLayout(10, 0)); // 水平间距10像素
            
            JTextField textField = new JTextField();
            textField.setPreferredSize(new Dimension(200, 30)); // 固定高度30
            
            JButton button = new JButton(buttonText);
            button.setPreferredSize(new Dimension(80, 30));    // 固定高度30
            
            panel.add(textField, BorderLayout.CENTER);
            panel.add(button, BorderLayout.EAST);
            
            return panel;
        }
    }
}
相关推荐
hrrrrb8 小时前
【Python】文件处理(二)
开发语言·python
先知后行。9 小时前
QT实现计算器
开发语言·qt
掘根9 小时前
【Qt】常用控件3——显示类控件
开发语言·数据库·qt
GUIQU.9 小时前
【QT】嵌入式开发:从零开始,让硬件“活”起来的魔法之旅
java·数据库·c++·qt
万粉变现经纪人11 小时前
如何解决 pip install 安装报错 ModuleNotFoundError: No module named ‘tokenizers’ 问题
python·selenium·测试工具·scrapy·beautifulsoup·fastapi·pip
西阳未落13 小时前
C++基础(21)——内存管理
开发语言·c++·面试
编程武士13 小时前
从50ms到30ms:YOLOv10部署中图像预处理的性能优化实践
人工智能·python·yolo·性能优化
我的xiaodoujiao13 小时前
Windows系统Web UI自动化测试学习系列2--环境搭建--Python-PyCharm-Selenium
开发语言·python·测试工具
callJJ13 小时前
从 0 开始理解 Spring 的核心思想 —— IoC 和 DI(2)
java·开发语言·后端·spring·ioc·di
wangjialelele13 小时前
Linux中的线程
java·linux·jvm·c++