Wednesday, November 16, 2011

JAVA CODE FOR VARIOUS DIALOG BOXES



import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.UIManager;

public class TestDialogue extends JFrame implements ActionListener {
    JButton button1 =null;
    JButton button2 =null;
    JButton button3 =null;

  public TestDialogue() throws HeadlessException {
    setSize(200, 200);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    button1 = new JButton("Simple Message dialog");
    button2 = new JButton("Dialog with InputBox");
    button3 = new JButton("Yes/No dialog");

    setLayout(new FlowLayout(FlowLayout.CENTER));
    getContentPane().add(button1);
    getContentPane().add(button2);
    getContentPane().add(button3);

    button1.addActionListener(this);
    button2.addActionListener(this);
    button3.addActionListener(this);
  }

  public static void main(String[] rk) {
        try
 {
  UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
 }catch(Exception e)
        {}
        new TestDialogue().setVisible(true);
  }

    @Override
    public void actionPerformed(ActionEvent e) {
    String Action;
    Action = e.getActionCommand ();

        if(Action.equals("Simple Message dialog")){
            JOptionPane.showMessageDialog((Component) e.getSource(), "Hello ! Thank you!");

        }else if(Action.equals("Dialog with InputBox")){
            String name = JOptionPane.showInputDialog((Component) e.getSource(), "Hello, please Input your name.");
            if (name != null && !name.equals("")) {
                JOptionPane.showMessageDialog((Component) e.getSource(), "Hi, " + name);
            }

        }else if(Action.equals("Yes/No dialog")){

            int result = JOptionPane.showConfirmDialog((Component) e.getSource(), "Close this application?");
            if (result == JOptionPane.YES_OPTION) {
            System.exit(0);
            } else if (result == JOptionPane.NO_OPTION) {
            System.out.println("No Action performed.");

        }
       }

    }
}

Enhanced by Zemanta

No comments:

Post a Comment