Copy the code code as follows:
package test001;
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.JToolBar;
public class TestJOptionPane implements ActionListener{
private JFrame jf = new JFrame("Standard dialog box test");
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new TestJOptionPane().createUI();
}
public void createUI(){
JToolBar jtb = new JToolBar();
String[] s = {"Error", "Exit Confirmation 1", "Exit Confirmation 2", "Warning", "Input", "Select"};
int size = s.length;
JButton[] button = new JButton[size];
for(int i = 0; i < size; i++){
button[i] = new JButton(s[i]);
button[i].addActionListener(this);
jtb.add(button[i]);
}
jf.add(jtb, "North");
jf.setSize(350, 150);
jf.setLocation(400, 200);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String s = e.getActionCommand();
if(s.equals("Error")){
JOptionPane.showMessageDialog(null, "Error message to be displayed---",
"Error message",JOptionPane.ERROR_MESSAGE);
}
else if(s.equals("Exit confirmation 1")){
int result = JOptionPane.showConfirmDialog(null,
"Save the program before launching?");
if(result == JOptionPane.YES_OPTION){
System.out.println("Save program---");
System.exit(0);
}
else if(result == JOptionPane.NO_OPTION){
System.exit(0);
}
}
else if(s.equals("Exit confirmation 2")){
int result = JOptionPane.showConfirmDialog(null, "Save the program before exiting?");
if(result == JOptionPane.YES_OPTION){
System.out.println("Save program---");
System.exit(0);
}
else if(result == JOptionPane.NO_OPTION){
System.exit(0);
}
}
else if(s.equals("warning")){
Object[] options = {"Continue", "Undo"};
int result = JOptionPane.showOptionDialog(null,
"This operation may result in data loss","Warning", JOptionPane.DEFAULT_OPTION,
JOptionPane.WARNING_MESSAGE, null, options, options[0]);
if(result == 0){
System.out.println("Continue operation---");
}
}
else if(s.equals("input")){
String name = JOptionPane.showInputDialog("Please enter your name:");
if(name != null){
System.out.println("Name: " + name);
}
}
else if(s.equals("select")){
Object[] possibleValues = {"Sports", "Politics", "Economy", "Culture"};
Object selectedValue = JOptionPane.showInputDialog(null,
"Choose one","Input", JOptionPane.INFORMATION_MESSAGE, null,
possibleValues, possibleValues[0]);
String choose = (String)selectedValue;
if(choose != null){
System.out.println("What you chose is: "+ choose);
}
}
}
}