【问题标题】:Java, Drop-down list of integersJava,整数下拉列表
【发布时间】:2018-02-24 04:58:38
【问题描述】:

我正在尝试创建一个下拉列表以请求用户魅力修饰符。

我目前正在使用 Java Swing 提供的下拉列表。 我使用的下拉列表可以找到here

这是我的代码:

import javax.swing.JOptionPane;

public class Character_Charisma
{
    private static String input = "";

    public static int main() {
        int[] choices = {-4, -3, -2, -1, 0, 1, 2, 3, 4, 5};
        int input = (int) JOptionPane.showInputDialog(null, "Choose now...",
            "What is your Charisma modifier?", JOptionPane.QUESTION_MESSAGE, null, 
                                                                    // Use
                                                                    // default
                                                                    // icon
            choices, // Array of choices
            choices[0]); // Initial choice
            return input;
    }
}

我正在努力用这段代码返回一个整数。

我收到错误消息:“不兼容的类型:int[] 无法转换为 java.lang.Object[]”

我做错了什么?

【问题讨论】:

  • 您是否阅读过有关如何构建 Swing GUI 程序的教程?您缺少一些基础知识,您不能只在非 GUI 程序中实例化 JOptionPane,需要一定数量的代码才能让 GUI 和事件循环运行,而您已经省略了。
  • 我已经让 Swing GUI 为其他一些字符串输入工作。目前它对我需要的东西运作良好。我正在使用 BlueJ 编写我的程序。

标签: java arrays integer dropdown


【解决方案1】:

请改用 Integer,因为它继承自 Object 类。:

import javax.swing.JOptionPane;

public class Character_Charisma
{
    private static String input = "";

    public static int main() {
        Integer[] choices = {-4, -3, -2, -1, 0, 1, 2, 3, 4, 5};
        Integer input = (Integer) JOptionPane.showInputDialog(null, "Choose now...",
            "What is your Charisma modifier?", JOptionPane.QUESTION_MESSAGE, null, 
                                                                    // Use
                                                                    // default
                                                                    // icon
            choices, // Array of choices
            choices[0]); // Initial choice
            return input;
    }
}

【讨论】:

  • 非常感谢,我知道这很简单。
  • 我无法投票,因为我的声望低于 15。
  • 不,你可以投票,可能是因为有人已经投票了!我怀疑他/她拒绝投票的理由是正确的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-20
  • 1970-01-01
  • 2014-09-28
  • 2011-07-19
相关资源
最近更新 更多