As I mentioned in my JOptionPane showMessageDialog examples, you can easily create a JOptionPane
dialog that shows a Java component. The component you show can be a JPanel a JScrollPane JLabel and many more things, anything that extends JComponent.
(The showMessageDialog
method actually lets you add anything that is an instance of a Java Object
, but as a practical matter, the only objects I can remember displaying in a JOptionPane
dialog like this are Swing/GUI objects that extend JComponent
.)
JOptionPane showMessageDialog component example
Here's the source code for a complete Java class that demonstrates how to show a JPanel
in a JOptionPane
dialog. This JOptionPane
example displays a JPanel
which I've given a blue background, and a minimum size of 200 pixels wide by 200 pixels tall:
import java.awt.Color; import java.awt.Dimension; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; /** * A JOptionPane showMessageDialog example that shows * how to display a component (JComponent) in a * JOptionPane dialog. */ public class ShowMessageDialogComponentExample { public static void main(String[] args) { // create a simple jpanel JPanel panel = new JPanel(); panel.setBackground(Color.BLUE); panel.setMinimumSize(new Dimension(200,200)); // display the jpanel in a joptionpane dialog, using showMessageDialog JFrame frame = new JFrame("JOptionPane showMessageDialog component example"); JOptionPane.showMessageDialog(frame, panel); System.exit(0); } }
When this JOptionPane
example is compiled and run, it displays a JOptionPane
dialog that looks like this:
Hopefully this is a simple example -- but a cool one -- because once you realize you can show any JComponent
you want in a JOptionPane
dialog, what you can achieve now is only limited by your creativity and imagination.
Three JOptionPane showMessageDialog method signatures
I showed the showMessageDialog
signature in my earlier JOptionPane showMessageDialog tutorial, but it is also useful to show those three different showMessageDialog
method signatures here as well. The first showMessageDialog
method signature looks like this:
showMessageDialog(Component parentComponent, Object message)
The second JOptionPane
showMessageDialog
method looks like this:
showMessageDialog(Component parentComponent, Object message, String title, int messageType)
And the third JOptionPane
showMessageDialog
method signature looks like this:
showMessageDialog(Component parentComponent, Object message, String title, int messageType, Icon icon)
Note that each of these JOptionPane showMessageDialog
methods allow the Object message
parameter, which is the parameter I pass into the method to display a component.