java - 我正在使用 java swing 概念。组合框的值类似于“GST 18.00%”。我只需要 (18.00) 作为浮点数。有什么办法可以完成这项任务
问题描述
我正在使用 java swing 概念。组合框的值类似于“GST 18.00%”。我只需要 (18.00) 作为浮点数。有什么办法可以完成这项任务...
解决方案
Do not add Strings to your ComboBox. Instead, create a value class and add instances of that.
Swing calls the toString() method of model objects in order to render them; you can take advantage of that by overriding that method in your value class:
public class GSTValue {
private final float rate;
public GSTValue(float rate) {
this.rate = rate;
}
public float getRate() {
return rate;
}
@Override
public boolean equals(Object obj) {
return obj instanceof GSTValue &&
((GSTValue) obj).rate == this.rate;
}
@Override
public int hashCode() {
return Objects.hashCode(rate);
}
@Override
public String toString() {
return String.format("GST %.2f%%", rate);
}
}
Then you can add the values directly to your JComboBox:
GSTValue rates = {
new GSTValue(5),
new GSTValue(12),
new GSTValue(18),
new GSTValue(28),
};
JComboBox<GSTValue> rateComboBox = new JComboBox<>(rates);
And you can easily retrieve that value at runtime:
GSTValue selection = (GSTValue) rateComboBox.getSelectedItem();
float rate = selection.getRate();
推荐阅读
- html - 无法手动将输入范围值设置为零
- python - Python:获取使用运行 Windows 但处理来自 Linux 的文件的脚本创建的日期
- python - spyder IDE 上的无效语法 (pyflakes E)
- node.js - 通过在查询字符串上使用 ${variable} 进行节点和 SQL 注入
- unity3d - 了解 GazeProvider GazeDirection Vector3
- r - parse_stream 似乎没有将我的 json 文件转换为数据框。它给我的结果是空的
- react-native - 世博会和地铁捆绑器:外部模块无法解析反应导入
- php - Laravel:使用 MariaDB 10.6 的 Docker 上的“alter table ...”连接被拒绝
- javascript - Amazon S3 - 管道字符串以在 nodejs 中的 S3 存储桶上上传多个字符串
- python - 在 Treeview 中,我只显示一行的 ID,而不显示剩余(空)字段