Saturday, September 13, 2008


Swing Input Dialog Box

Input dialog box in java is the good example of user input example in GUI environment. A user can input value at run time in small window. The input box also contains "OK" and "Cancel" button. The code below is the example to create an input box where user enter either text or numeric value at run time :

import javax.swing.*;
import java.awt.event.*;

public class ShowInputDialog{
public static void main(String[] args){
JFrame frame = new JFrame("Input Dialog Box Example");
JButton button = new JButton("Click for Input Dialog Box");
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
String txt = JOptionPane.showInputDialog(null, "Enter Your Text : ",
"Input Box", 1);
if(txt != null)
JOptionPane.showMessageDialog(null, "The text you have entered : " + txt,
"Input Box", 1);
else
JOptionPane.showMessageDialog(null, "You clicked on cancel button.",
"Input Box", 1);
}
});
JPanel panel = new JPanel();
panel.add(button);
frame.add(panel);
frame.setSize(350, 350);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}


0 comments: