我想实现一个组合框,显示了一天的每一个小时的名单,但没有成功。 它给了我“构造的JComboBox(JSpinner的)是未定义”的错误。 任何帮助吗? 谢谢
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 24);
calendar.set(Calendar.MINUTE, 0);
SpinnerDateModel model = new SpinnerDateModel();
model.setValue(calendar.getTime());
JSpinner spinner = new JSpinner(model);
departureTime = new JComboBox<String>(spinner);
不,这是没有意义的。 你应该通过一个组合框ComboBoxModel
填充想要显示的值
请参阅如何使用组合框和如何使用纱厂了解更多详情
您可以使用像这样它使用JSpinner
来显示时间,并允许用户对其进行操作
或者你需要在你希望用户被允许选择,诸如给定的时间间隔的数值,以填补组合框...
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
Calendar end = Calendar.getInstance();
end.set(Calendar.HOUR_OF_DAY, 23);
end.set(Calendar.MINUTE, 59);
DefaultComboBoxModel<Date> model = new DefaultComboBoxModel<>();
do {
model.addElement(calendar.getTime());
calendar.add(Calendar.MINUTE, 15);
} while (calendar.getTime().before(end.getTime()));
JComboBox<Date> cb = new JComboBox<>(model);
cb.setRenderer(new DateFormattedListCellRenderer(new SimpleDateFormat("HH:mm")));
add(cb);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
public class DateFormattedListCellRenderer extends DefaultListCellRenderer {
private DateFormat format;
public DateFormattedListCellRenderer(DateFormat format) {
this.format = format;
}
@Override
public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
if (value instanceof Date) {
value = format.format((Date) value);
}
return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
}
}
}
}
我不知道什么ü想与日历做,但每天有24个小时,添加列表在24小时或者创建拥有MAXVALUE 24的好手。