Java swing standards dialog box implementation
- 2020-04-01 02:05:52
- OfStack
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 testing ");
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 the confirmation 1", " Exit the confirmation 2", " warning ", " The input ", " choose "};
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 display ---",
" Error message ",JOptionPane.ERROR_MESSAGE);
}
else if(s.equals(" Exit the confirmation 1")){
int result = JOptionPane.showConfirmDialog(null,
" Is the program saved before rollout? ");
if(result == JOptionPane.YES_OPTION){
System.out.println(" Save the program ---");
System.exit(0);
}
else if(result == JOptionPane.NO_OPTION){
System.exit(0);
}
}
else if(s.equals(" Exit the confirmation 2")){
int result = JOptionPane.showConfirmDialog(null, " Do you save the program before exiting? ");
if(result == JOptionPane.YES_OPTION){
System.out.println(" Save the program ---");
System.exit(0);
}
else if(result == JOptionPane.NO_OPTION){
System.exit(0);
}
}
else if(s.equals(" warning ")){
Object[] options = {" Continue to ", " 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 to operate ---");
}
}
else if(s.equals(" The input ")){
String name = JOptionPane.showInputDialog(" Please enter your name: ");
if(name != null){
System.out.println(" Name: " + name);
}
}
else if(s.equals(" choose ")){
Object[] possibleValues = {" sports ", " political ", " economic ", " 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 choose is: "+ choose);
}
}
}
}