gpt4 book ai didi

java - 比较两个 JComboBox 的值

转载 作者:行者123 更新时间:2023-12-02 07:08:33 24 4
gpt4 key购买 nike

快速提问。我有两个 JComboBox,其中填充了从 2010 年到 2018 年的一串年份。一个组合框与“开始日期”标签关联,一个组合框与“结束日期”标签关联。我想确保“结束日期”中选择的年份小于“开始日期”中选择的年份。我已经查找了如何比较组合框值的方法,但我只是找不到适合我的具体示例的方法。

这是一些代码:

String[] YEARS = {"Select a Year", "2010", "2011", "2012", "2013", "2014", 
"2015", "2016", "2017", "2018",};

//Start Date
yearLong = new JComboBox(YEARS);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 3;
c.gridy = 1;
c.gridwidth = 1;
yearLong.setSelectedItem(Integer.toString(year));
pane.add(yearLong, c);
//End Date
yearLong1 = new JComboBox(YEARS);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 3;
c.gridy = 3;
c.gridwidth = 1;
pane.add(yearLong1, c);

为了向您证明我已经尝试过一些事情,到目前为止我已经完成了错误检查:

 //Checks to see if the End Date precedes the Start Date
} else if ((yearLong.getSelectedItem() > yearLong1.getSelectedItem())) {
JOptionPane.showMessageDialog(null, "Error 10: The End Date cannot precede the Start Date.",
"Error!",
JOptionPane.ERROR_MESSAGE);
return;
}

但是我不断收到错误消息,指出无法在那里使用 > 操作。我知道 == 操作可以,所以我不确定我做错了什么?

一如既往,感谢您的帮助!

最佳答案

错误的原因是getSelectedItem()实际上返回了Object,它没有定义运算符>

由于您使用字符串填充了组合,因此在比较日期时应将字符串转换为整数。您可以使用 Integer.parseInt() 方法。只需确保正确处理“Select a Year”字符串即可。如果需要,您还可以使用整数填充组合框,它在其构造函数中接受 Object 数组。请参阅How to Use Combo Boxes了解更多详细信息和示例。

关于java - 比较两个 JComboBox 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15816714/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com