运行后的样式
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;
}
}
}