Search code examples
javaswingjpaneljoptionpane

JOptionPane using JPanel


I am trying to use JPanel with JOptionPanel so that I can modify the size of the alert window. I have written the code as this:

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

However, when I run the program, the description is meant to be in the middle but instead, it goes into the title bar. How can I make this work so that the description is the main text of the alert window?


Solution

  • The JavaDocs for showMessageDialog clearly state that the third paramter is the title ("the title string for the dialog") of the dialog

    Instead, create a JLabel whose text is set to what you want to display and add it it the 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);
    }