java - 当值为-1时如何设置JSpinner显示“无限”?
问题描述
我有一个 JSpinner,它从 n 倒数到 0。但是,如果值为 -1,我希望隐藏该数字,而是显示“Infinite”或“∞”。当我检索该值时,它仍将读取为-1。
这可能吗,并且通过使用 SpinnerNumberModel?
谢谢,
蚂蚁
解决方案
AbstractFormatter
您可以为 的实现自己JFormattedTextField
的。这负责将s 转换为值并将值转换为s。DefaultEditor
JSpinner
String
String
以下是自定义格式化程序解决方案的一些示例代码:
import java.text.ParseException;
import java.util.Objects;
import javax.swing.JFormattedTextField;
import javax.swing.JFormattedTextField.AbstractFormatter;
import javax.swing.JFormattedTextField.AbstractFormatterFactory;
import javax.swing.JFrame;
import javax.swing.JSpinner;
import javax.swing.JSpinner.DefaultEditor;
import javax.swing.SpinnerNumberModel;
public class FormatterMain {
public static class CustomFormatter extends AbstractFormatter {
private static final String INFINITE_TEXT = "Infinite";
private static final Object INFINITE_VALUE = -1;
@Override
public Object stringToValue(final String text) throws ParseException {
try {
if (Objects.equals(text, INFINITE_TEXT))
return INFINITE_VALUE;
return Integer.valueOf(text);
}
catch (final NumberFormatException nfx) {
//Find where in the string is the parsing error (so as to return ParseException accordingly).
int i = 0;
for (final int cp: text.codePoints().toArray()) {
if (!Character.isDigit(cp))
throw new ParseException("Not a digit.", i);
++i;
}
//Should not happen:
throw new ParseException("Failed to parse input \"" + text + "\".", 0);
}
}
@Override
public String valueToString(final Object value) throws ParseException {
if (Objects.equals(value, INFINITE_VALUE))
return INFINITE_TEXT;
return Objects.toString(value);
}
}
public static class CustomFormatterFactory extends AbstractFormatterFactory {
@Override
public AbstractFormatter getFormatter(final JFormattedTextField tf) {
if (!(tf.getFormatter() instanceof CustomFormatter))
return new CustomFormatter();
return tf.getFormatter();
}
}
public static void main(final String[] args) {
final JSpinner spin = new JSpinner(new SpinnerNumberModel(0, -1, Integer.MAX_VALUE, 1));
((DefaultEditor) spin.getEditor()).getTextField().setFormatterFactory(new CustomFormatterFactory());
final JFrame frame = new JFrame("JSpinner infinite value");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(spin);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
推荐阅读
- python-3.x - 在 Jupiter notebook 中使用 ams 数学风格
- aws-cdk - (@aws-cdk/pipelines) 应用程序源代码的构建阶段
- javascript - 在 firestore 的新子集合中创建新文档时出错
- html - 如何使用 colspan 属性获取右侧的单元格?
- regex - 正则表达式在 Pythex.com 中有效,但在 pandas 中无效
- swift - 使用 Swift 对 Unsplashed 的 API 调用中缺少数据
- html - 如何在 span 标签中添加两个类?
- assembly - MIPS bne 汇编指令在 Microchip XC32 下无法正确执行
- vaadin - 在 LitTemplate 中使用 Vaadin 的 AbstractField、AbstractCompositeField 和 Composite
- python - 你如何在 python 的不同行上引用一个字符串?