Java Swing 自定义JOptionPane

运行后的样式

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;
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值