gpt4 book ai didi

java - 如何设置JSpinner在值为-1时显示 "Infinite"?

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

我有一个 JSpinner,它从 n 倒数到 0。但是,如果值为 -1,我希望隐藏该数字并显示“Infinite”或“∞”。当我检索该值时,它仍将读取为 -1。

通过使用 SpinnerNumberModel 这可能吗?

谢谢

Ant

最佳答案

您可以为 JSpinnerDefaultEditorJFormattedTextField 实现自己的 AbstractFormatter。它负责将 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);
}
}

关于java - 如何设置JSpinner在值为-1时显示 "Infinite"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52710619/

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