我正在使用 Swing 库和 Java 语言来实现我的项目的 GUI。我想通过用户友好的文本(例如“每 15 分钟”)从用户那里获取间隔,但在存储数据中,我必须将其保存为以秒为单位的数字。你可以查看我的 GUI:
我知道我可以通过为组合框编写一个项目监听器来解决这个问题,并为每个可能的项目编写一个 if else ,但我想了解是否有更实用的方法来做到这一点?因为我必须在程序中使用 4 个组合框。
谢谢。
最佳答案
您可以为 JComboBox
中的项目使用自定义类。来自 The Java Tutorials - How to Use Combo Boxes :
"The default renderer knows how to render strings and icons. If you put other objects in a combo box, the default renderer calls the toString method to provide a string to display."
如果您使用实现 toString
方法的自定义类,则可以向项目添加更多数据(例如以秒为单位的间隔持续时间)。例如(使用 Java 8):
// Class ComboBoxTextAndNumber:
import java.awt.event.ItemEvent;
import java.util.*;
import java.util.Vector;
import javax.swing.*;
public class ComboBoxTextAndNumber {
public static void main(final String[] arguments) {
SwingUtilities.invokeLater(
() -> new ComboBoxTextAndNumber().createAndShowGui()
);
}
private void createAndShowGui() {
final JFrame frame = new JFrame("Stack Overflow");
frame.setBounds(100, 100, 800, 600);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
final Vector<Interval> intervals = new Vector<>(Arrays.asList(
new Interval("every 5 years", 5 * 365 * 24 * 60 * 60),
new Interval("every day", 24 * 60 * 60))
);
final JPanel panel = new JPanel();
final JComboBox<Interval> comboBox = new JComboBox<>(intervals);
panel.add(comboBox);
frame.getContentPane().add(panel);
comboBox.addItemListener(
itemEvent -> {
if (itemEvent.getStateChange() == ItemEvent.SELECTED) {
final Interval interval = (Interval) comboBox.getSelectedItem();
System.out.println(interval.getSeconds());
}
}
);
frame.setVisible(true);
}
}
// Class Interval:
public class Interval {
private final String description;
private final long seconds;
public Interval(final String description, final long seconds) {
this.description = description;
this.seconds = seconds;
}
public String getDescription() {
return description;
}
public long getSeconds() {
return seconds;
}
@Override
public String toString() {
return getDescription();
}
}
关于java - 组合框以用户友好的方式获取数据并将其设置为数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33987740/