如何在 Java 中将 JOptionPane 与数组元素配合使用?
让我们先创建一个数组并添加元素 -
String[] sports = { "Football", "Cricket", "Squash", "Baseball", "Fencing", "Volleyball", "Basketball" };
现在,将上述数组元素设置为 JOptionPane -
String res = (String) JOptionPane.showInputDialog(null, "Which sports you play the most?", "Sports", JOptionPane.PLAIN_MESSAGE, null, sports, sports[0]);
上面,我们还设置了初始值,即 sports(0)。
以下是一个在 Java 中将 JOptionPane 与数组元素配合使用的示例 -
示例
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; } } }
输出
现在从上面选择任何一项并单击确定,以在控制台中显示所选的项。我们选择了“排球” -
上面选择的选项在控制台中可见 -
广告