首页 > 解决方案 > 我正在使用 java swing 概念。组合框的值类似于“GST 18.00%”。我只需要 (18.00) 作为浮点数。有什么办法可以完成这项任务

问题描述

我正在使用 java swing 概念。组合框的值类似于“GST 18.00%”。我只需要 (18.00) 作为浮点数。有什么办法可以完成这项任务...

标签: javaswing

解决方案


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();

推荐阅读