1.使用JOptionPane提示用户确认
import javax.swing.JOptionPane;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
public class JOptionPaneTest2 {
public static void main(String[] args) {
JDialog.setDefaultLookAndFeelDecorated(true);
int response = JOptionPane.showConfirmDialog(null, "Do you want to continue?", "Confirm",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (response == JOptionPane.NO_OPTION) {
System.out.println("No button clicked");
} else if (response == JOptionPane.YES_OPTION) {
System.out.println("Yes button clicked");
} else if (response == JOptionPane.CLOSED_OPTION) {
System.out.println("JOptionPane closed");
}
}
}
2.使用JOptionPane预先选
import javax.swing.JDialog;
import javax.swing.JOptionPane;
public class JOptionPaneTest3 {
public static void main(String[] args) {
JDialog.setDefaultLookAndFeelDecorated(true);
Object[] selectionValues = { "Pandas", "Dogs", "Horses" };
String initialSelection = "Dogs";
Object selection = JOptionPane.showInputDialog(null, "What are your favorite animals?",
"Zoo Quiz", JOptionPane.QUESTION_MESSAGE, null, selectionValues, initialSelection);
System.out.println(selection);
}
}
3.获取用户选择JOptionPane
import javax.swing.JDialog;
import javax.swing.JOptionPane;
public class GettingJOptionPaneSelectionDemo {
public static void main(String[] a) {
String multiLineMsg[] = { "Hello,", "World" };
JOptionPane pane = new JOptionPane();
pane.setMessage(multiLineMsg);
JDialog d = pane.createDialog(null, "title");
d.setVisible(true);
int selection = getSelection(pane);
switch (selection) {
case JOptionPane.OK_OPTION:
System.out.println("OK_OPTION");
break;
case JOptionPane.CANCEL_OPTION:
System.out.println("CANCEL");
break;
default:
System.out.println("Others");
}
}
public static int getSelection(JOptionPane optionPane) {
int returnValue = JOptionPane.CLOSED_OPTION;
Object selectedValue = optionPane.getValue();
if (selectedValue != null) {
Object options[] = optionPane.getOptions();
if (options == null) {
if (selectedValue instanceof Integer) {
returnValue = ((Integer) selectedValue).intValue();
}
} else {
for (int i = 0, n = options.length; i < n; i++) {
if (options[i].equals(selectedValue)) {
returnValue = i;
break; // out of for loop
}
}
}
}
return returnValue;
}
}