Swing JOptionPane : Class



Swing JOptionPane Class :

package com.c4learn.swing;

import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class JOptionPaneDemo {

  private JFrame mainFrame;
  private JLabel headLabel;
  private JLabel msgLabel;
  private JPanel mainPanel;

  public JOptionPaneDemo() {
    mainFrame = new JFrame("Java Swing Examples");
    mainFrame.setSize(400, 400);
    mainFrame.setLayout(new GridLayout(3, 1));

    headLabel = new JLabel("Optionpane Demo", JLabel.CENTER);
    msgLabel = new JLabel("No Action", JLabel.CENTER);
    mainPanel = new JPanel();
    mainPanel.setLayout(new FlowLayout());

    mainFrame.add(headLabel);
    mainFrame.add(mainPanel);
    mainFrame.add(msgLabel);
    mainFrame.setVisible(true);
  }

  public static void main(String[] args) {
    JOptionPaneDemo demo = new JOptionPaneDemo();
    demo.optionPaneDemo();
  }

  private void optionPaneDemo() {

    JButton okButton = new JButton("Message Box");

    okButton.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {

        int optn = JOptionPane.showConfirmDialog(mainFrame,
            "Click any button", "Option Pane",
            JOptionPane.YES_NO_CANCEL_OPTION,
            JOptionPane.INFORMATION_MESSAGE);

        if (optn == JOptionPane.YES_OPTION) {
          msgLabel.setText("Yes Selected.");
        } else if (optn == JOptionPane.NO_OPTION) {
          msgLabel.setText("No Selected.");
        } else if (optn == JOptionPane.CANCEL_OPTION) {
          msgLabel.setText("Cancel Selected.");
        }
      }
    });

    mainPanel.add(okButton);
    mainFrame.setVisible(true);
  }
}

Output :

Swing JOptionPane 1
Swing JOptionPane 2