Thursday, February 13, 2014

Simple example to display message dialog with JOptionPane

The showMessageDialog(Component parentComponent, Object message) method of JOptionPane display an information-message dialog.

where:
parentComponent - determines the Frame in which the dialog is displayed; if null, or if the parentComponent has no Frame, a default Frame is used.
message - the Object to display

JOptionPane
display message dialog with JOptionPane

package javajoptionpane;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaJOptionPane extends JFrame{
    
    public void prepareUI() {
        JPanel hPanel = new JPanel();
        hPanel.setLayout(new BoxLayout(hPanel, BoxLayout.X_AXIS));
        
        JButton jButton = new JButton("showMessageDialog");
        jButton.setVerticalTextPosition(JButton.BOTTOM);
        jButton.setHorizontalTextPosition(JButton.RIGHT);
        
        jButton.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(
                        null, 
                        "It's JOptionPane");
            }
        });

        hPanel.add(jButton);
        getContentPane().add(hPanel, BorderLayout.CENTER);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                createAndShowGUI();
            }
        });
    }
    
    private static void createAndShowGUI() {
        JavaJOptionPane myJavaJOptionPane = new JavaJOptionPane();
        myJavaJOptionPane.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myJavaJOptionPane.prepareUI();
        myJavaJOptionPane.pack();
        myJavaJOptionPane.setVisible(true);
    }
}

No comments:

Post a Comment