Mega Code Archive

 
Categories / Java Tutorial / Swing
 

The JOptionPane Message Argument is an Object, not a String

If the message is an array of objects (Object[ ]), make the JOptionPane place each entry onto a separate row. If the message is a Component, place the component in the message area. If the message is an Icon, place the Icon within a JLabel and display the label in the message area. If the message is an Object, convert it to a String with toString(), place the String in a JLabel, and display the label in the message area. import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; public class Test2 extends JFrame {   public Test2() {     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);     getContentPane().add(new JLabel("Placeholder label"));     pack();     setSize(200, 200);     setVisible(true);     Object msg[] = { "Complex Message", new JButton("A component"),         new Object[] { "  Nested", "  Array" }, "for JOptionPane" };     Object type[] = { "Animal", "Vegetable", "Mineral" };     int result = JOptionPane.showOptionDialog(this, msg, "Choose",         JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, type,         null);     System.out.println("Result (index)= " + result + " (" + type[result] + ")");   }   public static void main(String[] args) {     new Test2();   } }