使用 JPanel 的 JOptionPane

JOptionPane using JPanel

我正在尝试将 JPanelJOptionPanel 一起使用,以便我可以修改警报 window 的大小。我写的代码是这样的:

JPanel panel = new JPanel();
//panel.setBackground(Color.RED);
panel.setPreferredSize(new Dimension(500,500));

// display the jpanel in a joptionpane dialog, using showMessageDialog
JFrame frame = new JFrame("JOptionPane showMessageDialog component example");

while (AlarmRS.next()) {
    System.out.println(AlarmRS.getString("Description"));
    //JOptionPane.showInternalMessageDialog(null, getPanel(), AlarmRS.getString("Description"), JOptionPane.INFORMATION_MESSAGE);
    JOptionPane.showMessageDialog(frame,panel, AlarmRS.getString("Description"), JOptionPane.WARNING_MESSAGE);
}

但是,当我 运行 程序时,描述本来应该在中间,但它却进入了标题栏。我怎样才能使这项工作使描述成为警报的主要文本 window?

JavaDocs for showMessageDialog明确表示第三个参数是dialog

title("the title string for the dialog")

相反,创建一个 JLabel,其文本设置为您想要显示的内容,并将其添加到 panel

JPanel panel = new JPanel(new GridBagLayout());
//panel.setBackground(Color.RED);
panel.setPreferredSize(new Dimension(500, 500));

while (AlarmRS.next()) {
    System.out.println(AlarmRS.getString("Description"));
    panel.add(new JLabel(AlarmRS.getString("Description")));
    //JOptionPane.showInternalMessageDialog(null, getPanel(), AlarmRS.getString("Description"), JOptionPane.INFORMATION_MESSAGE);
    JOptionPane.showMessageDialog(frame, panel, "This is a title", JOptionPane.WARNING_MESSAGE);
}