如何在 Java 中创建输入弹出窗口(对话框),并从用户处获取输入?
使用 JOptionPane.showInputDialog() 从对话框获取用户输入,例如 “哪项运动你最擅长”, “你的名字是啥”,等等。以下是创建输入弹出窗口(对话框)并从用户处获取输入的示例 −
示例
package my; import javax.swing.JOptionPane; public class SwingDemo { public static void main(String[] args) { String[] sports = { "Football", "Cricket", "Squash", "Baseball", "Fencing", "Volleyball", "Basketball" }; String res = (String) JOptionPane.showInputDialog(null, "Which sports you play the most?", "Sports", JOptionPane.PLAIN_MESSAGE, null, sports, sports[0]); switch (res) { case "Football" − System.out.println("I Love Football"); break; case "Cricket" − System.out.println("I Love Cricket"); break; case "Squash" − System.out.println("I Love Squash"); break; case "Baseball" − System.out.println("I Love Baseball"); break; case "Fencing" − System.out.println("I Love Fencing"); break; case "Volleyball" − System.out.println("I Love Volleyball"); break; case "Basketball" − System.out.println("I Love Basketball"); break; } } }
输出
现在从上方任选一项,然后点击确定在控制台中显示所选项。
我们选择了 “排球” −
上述所选项显示在控制台中 −
广告