我过去一直在使用以下技术来禁用JSpinner
s 的编辑。但是,它似乎不适用于JTextField
in a DateEditor
。有没有理由editor.getTextField().setEditable(false)
在这种情况下不起作用?有没有办法让它工作?
司机班
public class CLIClockDriver {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new ClockFrame();
}
});
}
}
摇摆班
public class ClockFrame extends JFrame implements ActionListener {
private static final long serialVersionUID = -7009835158496820266L;
public static final Dimension SIZE = new Dimension(400, 200);
private final Timer secondsTimer = new Timer(1000, this);
private final FluentGridBagConstraints gbc = new FluentGridBagConstraints();
private JPanel mainPanel;
private JLabel clockLabel;
private JSpinner newAlarmHourSpinner, newAlarmMinuteSpinner, newAlarmAMPMSpinner;
public ClockFrame() {
super();
setLayout(new GridBagLayout());
initializeGUIComponents();
setPreferredSize(SIZE);
setResizable(false);
setTitle(Constants.APPLICATION_NAME);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
secondsTimer.start();
}
private void initializeGUIComponents() {
mainPanel = new JPanel(new GridBagLayout());
clockLabel = new JLabel();
updateClock();
mainPanel.add(clockLabel, gbc.setXY(0, 0));
newAlarmHourSpinner = new JSpinner();
newAlarmHourSpinner.setModel(new CyclingSpinnerNumberModel(9, 1, 12, 1));
DefaultEditor editor = new JSpinner.DefaultEditor(newAlarmHourSpinner);
editor.getTextField().setColumns(2);
editor.getTextField().setEditable(false);
newAlarmHourSpinner.setEditor(editor);
mainPanel.add(newAlarmHourSpinner, gbc.reset().setXY(0, 1));
newAlarmMinuteSpinner = new JSpinner();
SpinnerDateModel model = new SpinnerDateModel();
model.setCalendarField(Calendar.MINUTE);
newAlarmMinuteSpinner.setModel(model);
DateEditor dateEditor = new JSpinner.DateEditor(newAlarmMinuteSpinner, "mm");
editor.getTextField().setColumns(2);
editor.getTextField().setEditable(false);
newAlarmMinuteSpinner.setEditor(dateEditor);
mainPanel.add(newAlarmMinuteSpinner, gbc.reset().setXY(1, 1));
newAlarmAMPMSpinner = new JSpinner();
newAlarmAMPMSpinner.setModel(new CyclingSpinnerListModel("AM", "PM"));
editor = new JSpinner.DefaultEditor(newAlarmAMPMSpinner);
editor.getTextField().setColumns(2);
editor.getTextField().setEditable(false);
newAlarmAMPMSpinner.setEditor(editor);
mainPanel.add(newAlarmAMPMSpinner, gbc.reset().setXY(2, 1));
add(mainPanel, gbc.reset().setXY(0, 0));
}
private void updateClock() {
clockLabel.setText(Alarm.TIME_FORMAT.format(new Date()));
}
@Override
public void actionPerformed(ActionEvent event) {
if(event.getSource() == secondsTimer) {
updateClock();
}
}
}