This is my jComboBox:
这是我的jComboBox:
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "3", "4" }));
jComboBox1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox1ActionPerformed(evt);
}
I want to get the value selected that is 3
or 4
and convert it into float
?
我想获得3或4的选择值并将其转换为浮点数?
This is what I have tried:
这是我尝试过的:
a = Float.parseFloat(jComboBox1.getActionCommand());
but it doesn't seems to be working.
但它似乎没有起作用。
2 个解决方案
#1
1
You can get selected object(getSelectedItem()
method) and convert it to Float
like next:
您可以获取所选对象(getSelectedItem()方法)并将其转换为Float,如下所示:
Object o = jComboBox1.getSelectedItem();
Float floatValue = Float.valueOf(o.toString());
System.out.println(floatValue);
or at runtime you need to use ItemListener
:
或者在运行时,您需要使用ItemListener:
jComboBox1.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent event) {
if(event.getStateChange() == ItemEvent.SELECTED){
Object o = event.getItem();
Float floatValue = Float.valueOf(o.toString());
System.out.println(floatValue);
}
}
});
#2
1
You need to work with the value out of the JComboBox
, not the action Command. Specifically calling: getSelectedItem()
.
您需要使用JComboBox中的值,而不是action命令。具体调用:getSelectedItem()。
如何使用组合框
If you are only using Floats as options you can put the value in the combo box as Float objects so that you don't have to parse it on the way out.
如果您只使用Floats作为选项,则可以将值放在组合框中作为Float对象,这样您就不必在出路时解析它。
Example:
例:
JComboBox<Float> box = new JComboBox<Float>();
box.addItem(3f);
box.addItem(4f);
// something
Float selected = box.getItemAt(box.getSelectedIndex());
#1
1
You can get selected object(getSelectedItem()
method) and convert it to Float
like next:
您可以获取所选对象(getSelectedItem()方法)并将其转换为Float,如下所示:
Object o = jComboBox1.getSelectedItem();
Float floatValue = Float.valueOf(o.toString());
System.out.println(floatValue);
or at runtime you need to use ItemListener
:
或者在运行时,您需要使用ItemListener:
jComboBox1.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent event) {
if(event.getStateChange() == ItemEvent.SELECTED){
Object o = event.getItem();
Float floatValue = Float.valueOf(o.toString());
System.out.println(floatValue);
}
}
});
#2
1
You need to work with the value out of the JComboBox
, not the action Command. Specifically calling: getSelectedItem()
.
您需要使用JComboBox中的值,而不是action命令。具体调用:getSelectedItem()。
如何使用组合框
If you are only using Floats as options you can put the value in the combo box as Float objects so that you don't have to parse it on the way out.
如果您只使用Floats作为选项,则可以将值放在组合框中作为Float对象,这样您就不必在出路时解析它。
Example:
例:
JComboBox<Float> box = new JComboBox<Float>();
box.addItem(3f);
box.addItem(4f);
// something
Float selected = box.getItemAt(box.getSelectedIndex());