我用 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) 方法更新它。
我在行 Float newValue = (Float)resistorValue.getValue()*1000; 中收到 java.lang.ClassCastException: java.lang.Long 无法转换为 java.lang.Float;
以及 Float newValue = (Float)evt.getNewValue();
最佳答案
有两个区域
1) 不是Float
而是float
,
2) 我使用强制转换从 JFormattedTextField
3) float newValue = (((Number)sistorValue.getValue()).floatValue());
关于java - JFormattedTextField 和 NumberFormat 与 Float 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8254093/