我试图实现一个ComboBox,它显示当天每小时的列表,但没有成功。它给了我"构造函数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);
答案 0 :(得分:2)
不,这没有任何意义。您应该将组合框传递给ComboBoxModel
填充您想要显示的值
有关详细信息,请参阅How to use comboboxes和How to Use Spinners
您可以使用类似this的内容使用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);
}
}
}
}
答案 1 :(得分:1)
我不知道你想用日历做什么,但是每天都有24小时,所以添加一个24小时的列表或创建一个maxvalue 24的微调器。