我用JFormattedTextField做了一个小对话框,输入一个0到10之间的Float数,最多3个十进制数。我正在使用NumberFormat,并使用PropertyChangeListener来验证值或返回旧值。但它不起作用:
public class IRCompensationDialog extends JDialog{
private static final long serialVersionUID = 1L;
private JDialog irDialog;
private JButton cancelButton, okButton;
private JFormattedTextField resistorValue;
private INode nodo;
public IRCompensationDialog(int idNodo) throws BusinessException, ParseException{
super(MainFrame.getInstance());
this.irDialog = this;
this.setResizable(false);
this.setModal(true);
this.setTitle("IR Compensation");
this.nodo = new ServicesFactoryImpl().getNodesServices().getNode(idNodo);
initComponents();
this.pack();
this.setLocationRelativeTo(null);
this.setVisible(true);
}
private void initComponents() throws ParseException{
NumberFormat numberFormat = NumberFormat.getInstance();
numberFormat.setMaximumFractionDigits(3);
resistorValue = new JFormattedTextField(numberFormat);
resistorValue.addPropertyChangeListener("value", new IRValueChangeListener());
float currentValue = nodo.getIR() / 1000;
resistorValue.setValue(currentValue);
JPanel botonera = new JPanel();
cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
irDialog.setVisible(false);
}
});
botonera.add(cancelButton);
okButton = new JButton("OK");
okButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Float newValue = (Float)resistorValue.getValue()*1000;
nodo.setIR(newValue.intValue());
}
});
botonera.add(okButton);
this.setLayout (new BorderLayout());
this.add (resistorValue, BorderLayout.CENTER);
this.add (new JLabel("Enter resistor value (Ohms):"), BorderLayout.NORTH);
this.add (botonera, BorderLayout.SOUTH);
}
private class IRValueChangeListener implements PropertyChangeListener{
@Override
public void propertyChange(PropertyChangeEvent evt) {
JFormattedTextField field = (JFormattedTextField) evt.getSource();
Float newValue = (Float)evt.getNewValue().toString();
if(newValue>0 && newValue<=10000){
JOptionPane.showMessageDialog(MainFrame.getInstance(), " Value must be between 0 and 10 Ohm", "Error", JOptionPane.ERROR_MESSAGE);
Float oldValue = (Float) evt.getOldValue();
field.setValue(oldValue);
}
}
}
}
INode是我创建的一个类,它存储了我用getIR()方法得到的 int 值,并用setIR(int)方法更新它。
我收到java.lang.ClassCastException:java.lang.Long无法转换为行Float newValue = (Float)resistorValue.getValue()*1000;
中的java.lang.Float以及行Float newValue = (Float)evt.getNewValue();
答案 0 :(得分:3)
有两个方面
1)不是Float
而是float
,
2)我使用强制转换从JFormattedTextField
3)float newValue = (((Number) resistorValue.getValue()).floatValue());