如何实现两个JOptionPane并排显示以对比排序前后的数据
两个JOptionPane并排显示的实现方案
JOptionPane 调用默认showXxxDialog方法生成的弹窗会自动定位到父组件或屏幕中心,连续弹出就会出现层叠问题。要实现并排摆放,可通过手动控制Dialog坐标的方式实现,具体方案如下:
方案1:独立双弹窗手动控制位置
核心思路是不直接调用JOptionPane的快速展示方法,而是先生成对应的Dialog实例,自定义坐标后再显示:
- 分别构造排序前、排序后对应的JOptionPane实例
- 调用
createDialog()方法生成两个JDialog对象,自定义弹窗标题 - 基于屏幕/父窗口尺寸计算两个弹窗的摆放坐标,水平方向并排摆放,垂直方向居中对齐
- 依次设置两个弹窗可见
参考代码:
import javax.swing.*; import java.awt.*; public class SortCompareDialog { public static void main(String[] args) { // 替换为你实际的排序前后数据 String beforeContent = "排序前数据:\n9, 5, 2, 7, 1, 8, 3"; String afterContent = "排序后数据:\n1, 2, 3, 5, 7, 8, 9"; // 构造两个JOptionPane实例 JOptionPane beforePane = new JOptionPane(beforeContent, JOptionPane.INFORMATION_MESSAGE); JOptionPane afterPane = new JOptionPane(afterContent, JOptionPane.INFORMATION_MESSAGE); // 生成Dialog并设置标题 JDialog beforeDialog = beforePane.createDialog("排序前"); JDialog afterDialog = afterPane.createDialog("排序后"); // 计算摆放坐标 Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); int dialogWidth = 280; int dialogHeight = 180; int gap = 20; // 两个弹窗之间的间距 int totalWidth = dialogWidth * 2 + gap; // 左弹窗坐标 int beforeX = (screenSize.width - totalWidth) / 2; int centerY = (screenSize.height - dialogHeight) / 2; // 右弹窗坐标 int afterX = beforeX + dialogWidth + gap; // 设置弹窗尺寸和位置 beforeDialog.setBounds(beforeX, centerY, dialogWidth, dialogHeight); afterDialog.setBounds(afterX, centerY, dialogWidth, dialogHeight); // 显示弹窗 beforeDialog.setVisible(true); afterDialog.setVisible(true); } }
方案2:单弹窗内嵌并排面板(可选)
如果不需要严格两个独立弹窗,也可以把两个对比内容放在水平分割面板中,用单个弹窗展示,无需手动调整位置,对比更方便:
// 构造排序前后展示区域 JTextArea beforeArea = new JTextArea("排序前数据:\n9, 5, 2, 7, 1, 8, 3"); JTextArea afterArea = new JTextArea("排序后数据:\n1, 2, 3, 5, 7, 8, 9"); beforeArea.setEditable(false); afterArea.setEditable(false); // 水平分割面板承载两个内容区 JSplitPane comparePane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, beforeArea, afterArea); comparePane.setDividerLocation(140); // 直接弹出单个对比弹窗 JOptionPane.showMessageDialog(null, comparePane, "排序前后对比", JOptionPane.INFORMATION_MESSAGE);
注意事项
- 如果你的程序有父窗口,计算坐标时可基于父窗口的位置计算,适配性更强
- 两个弹窗建议设置相同尺寸,对比效果更直观
内容的提问来源于stack exchange,提问作者BigAinTX
相关产品推荐
相关产品推荐

