下面列出了怎么用javax.swing.JSpinner的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* CallBack triggered by a change in one of the spinners.
*
* @param e the change event, this allows to retrieve the originating
* spinner
*/
@Override
public void stateChanged (ChangeEvent e)
{
JSpinner spinner = (JSpinner) e.getSource();
// Nota: this method is automatically called whenever the spinner value
// is changed, including when a GLYPH selection notification is
// received leading to such selfUpdating. So the check.
if (!selfUpdating) {
// Notify the new glyph id
getSelectionService()
.publish(
new GlyphIdEvent(
this,
SelectionHint.GLYPH_INIT,
null,
(Integer) spinner.getValue()));
}
}
/** Creates new form CustomizerGeneral */
public CustomizerGeneral(CustomizerDataSupport custData) {
this.custData = custData;
initComponents();
JTextField serverPortTextField = ((JSpinner.NumberEditor) serverPortSpinner.getEditor()).getTextField();
AccessibleContext ac = serverPortTextField.getAccessibleContext();
ac.setAccessibleName(NbBundle.getMessage(CustomizerGeneral.class, "ASCN_ServerPort"));
ac.setAccessibleDescription(NbBundle.getMessage(CustomizerGeneral.class, "ASCD_ServerPort"));
JTextField shutdownPortTextField = ((JSpinner.NumberEditor) shutdownPortSpinner.getEditor()).getTextField();
ac = shutdownPortTextField.getAccessibleContext();
ac.setAccessibleName(NbBundle.getMessage(CustomizerGeneral.class, "ASCN_ShutdownPort"));
ac.setAccessibleDescription(NbBundle.getMessage(CustomizerGeneral.class, "ASCD_ShutdownPort"));
// work-around for jspinner incorrect fonts
Font font = usernameTextField.getFont();
serverPortSpinner.setFont(font);
shutdownPortSpinner.setFont(font);
}
private ControlsPanel() {
cmbPaint = createCombo(this, paintType);
cmbPaint.setSelectedIndex(1);
cmbCycle = createCombo(this, cycleMethod);
cmbSpace = createCombo(this, colorSpace);
cmbShape = createCombo(this, shapeType);
cmbXform = createCombo(this, xformType);
int max = COLORS.length;
SpinnerNumberModel model = new SpinnerNumberModel(max, 2, max, 1);
spinNumColors = new JSpinner(model);
spinNumColors.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
numColors = ((Integer)spinNumColors.getValue()).intValue();
gradientPanel.updatePaint();
}
});
add(spinNumColors);
cbAntialias = createCheck(this, "Antialiasing");
cbRender = createCheck(this, "Render Quality");
}
private void initSourceDestMotion(Motion m, JSpinner start, JCheckBox check, JSpinner dest, JComboBox motionType) {
if(m == null) {
check.setSelected(false);
start.setEnabled(false);
dest.setEnabled(false);
return;
}
start.setValue(m.getSourceValue());
//if(m.getSourceValue() != m.getDestinationValue()) {
check.setSelected(true);
motionType.setEnabled(true);
dest.setEnabled(true);
start.setEnabled(true);
//} else {
// check.setSelected(false);
//}
motionType.setSelectedIndex(AnimationAccessor.getMotionType(m) - 1);
dest.setValue(m.getDestinationValue());
}
/**
* Constructor.
*/
public SpinnerRangeDouble(double defValue, double minValue, double maxValue, double incValue, int visibleChars) {
super();
this.defValue = defValue;
this.minValue = minValue;
this.maxValue = maxValue;
this.incValue = incValue;
Double def = new Double(defValue);
Double min = new Double(minValue);
Double max = new Double(maxValue);
Double inc = new Double(incValue);
model = new SpinnerNumberModel(def, min, max, inc);
setModel(model);
JFormattedTextField tf = ((JSpinner.DefaultEditor) getEditor()).getTextField();
tf.setColumns(visibleChars);
}
/**
* Constructor.
*/
public SpinnerRangeFloat(float defValue, float minValue, float maxValue, float incValue, String format) {
super();
this.defValue = defValue;
this.minValue = minValue;
this.maxValue = maxValue;
this.incValue = incValue;
Double def = new Double(defValue);
Double min = new Double(minValue);
Double max = new Double(maxValue);
Double inc = new Double(incValue);
this.model = new SpinnerNumberModel(def, min, max, inc);
setModel(model);
setEditor(new JSpinner.NumberEditor(this, format));
JFormattedTextField tf = ((JSpinner.DefaultEditor) getEditor()).getTextField();
tf.setColumns(7);
}
@Override
public void reset() {
super.reset();
raceComboBox .setSelectedIndex( 0 );
leagueComboBox .setSelectedIndex( 0 );
matchResultComboBox.setSelectedIndex( 0 );
minApmSpinner.getEditor().setBackground( null );
restoreDefaultBackground( ( (JSpinner.NumberEditor) minApmSpinner.getEditor() ).getTextField() );
minApmSpinner.setValue( MIN_VALID_APM );
maxApmSpinner.getEditor().setBackground( null );
restoreDefaultBackground( ( (JSpinner.NumberEditor) maxApmSpinner.getEditor() ).getTextField() );
maxApmSpinner.setValue( MAX_VALID_APM );
}
/**
* Workaround for a swing bug : when the user enters an illegal value, the
* text is forced to the last value.
*
* @param spinner the spinner to update
*/
public static void fixIntegerList (final JSpinner spinner)
{
JSpinner.DefaultEditor editor;
editor = (JSpinner.DefaultEditor) spinner.getEditor();
final JFormattedTextField ftf = editor.getTextField();
ftf.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "enterAction");
ftf.getActionMap().put("enterAction", new AbstractAction()
{
@Override
public void actionPerformed (ActionEvent e)
{
try {
spinner.setValue(Integer.parseInt(ftf.getText()));
} catch (NumberFormatException ex) {
// Reset to last value
ftf.setText(ftf.getValue().toString());
}
}
});
}
/**
* Creates new form FileSelection
*/
public SimulationParameters() {
initComponents();
this.setResizable(false);
this.setTitle("File Selection");
fileReader = new FileRead();
initialiseDateComboBox(fileReader);
JSpinner.DateEditor timeEditor = new JSpinner.DateEditor(SpinnerTime, "HH:mm:ss");
DateFormatter formatter = (DateFormatter) timeEditor.getTextField().getFormatter();
formatter.setAllowsInvalid(false); // Make sure no invalid input is allowed
SpinnerTime.setEditor(timeEditor);
String StartTime = "08:30:00";
Date time;
try {
time = new SimpleDateFormat("HH:mm:ss").parse(StartTime);
SpinnerTime.setValue(time); // will only show the current time
} catch (ParseException ex) {
Logger.getLogger(SimulationParameters.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Constructs a new preferences panel.
*/
public
RemindersPanel()
{
super(PreferencesKeys.REMINDERS);
setSpinner(new JSpinner(new SpinnerNumberModel(0, 0, 21, 1)));
createButtons();
buildPanel();
// Initialize the panel with the selected reminder.
displayReminderInfo();
// Prevent users from entering arbitrary data in the spinner.
((JSpinner.NumberEditor)getSpinner().getEditor()).getTextField().setEditable(false);
// Add listeners.
getChooser().addTreeSelectionListener(new SelectionHandler());
getSpinner().addChangeListener(new ChangeHandler());
}
private void updatePagesToScan(Integer pagesToScan) {
JSpinner pagesToScanSpinner = components.getPagesToScanSpinner();
if (pagesToScan == null) {
pagesToScanSpinner.setEnabled(false);
} else {
pagesToScanSpinner.setEnabled(!(components.getBatchScanCheckBox().isSelected()));
pagesToScanSpinner.setValue(pagesToScan);
}
}
public SpinData (String label,
String tip,
SpinnerModel model)
{
this.label = new JLabel(label, SwingConstants.RIGHT);
spinner = new JSpinner(model);
SpinnerUtil.setRightAlignment(spinner);
SpinnerUtil.setEditable(spinner, true);
spinner.setToolTipText(tip);
}
HexaEditor (JSpinner spinner)
{
super(spinner);
JFormattedTextField ftf = getTextField();
ftf.setEditable(true);
ftf.setFormatterFactory(new HexaFormatterFactory());
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
lblTime1 = new javax.swing.JLabel();
spnTime1 = new javax.swing.JSpinner();
spnTime2 = new javax.swing.JSpinner();
setOpaque(false);
lblTime1.setText(org.openide.util.NbBundle.getMessage(TimeRangePanel.class, "DateCriteriaPanel.lblDate1.text")); // NOI18N
spnTime1.setModel(new javax.swing.SpinnerDateModel(new java.util.Date(1366083314466L), null, null, java.util.Calendar.HOUR));
spnTime2.setModel(new javax.swing.SpinnerDateModel(new java.util.Date(), null, null, java.util.Calendar.HOUR));
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(spnTime1, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(lblTime1)
.addGap(18, 18, 18)
.addComponent(spnTime2, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 30, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(0, 0, 0)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(spnTime1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lblTime1)
.addComponent(spnTime2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
);
}
@Override
public void createUI() {
this.startSpinner = new JSpinner();
this.addUIElement("Start", this.startSpinner);
this.endSpinner = new JSpinner();
this.addUIElement("End", this.endSpinner);
}
public LimitRowsCheckBoxActionListener(final JSpinner maxPreviewRowsSpinner)
{
this.maxPreviewRowsSpinner = maxPreviewRowsSpinner;
putValue(Action.NAME, Messages.getString("QueryPanel.LimitRowsCheckBox"));
putValue(Action.MNEMONIC_KEY, Messages.getMnemonic("QueryPanel.LimitRowsCheckBox.Mnemonic"));
maxPreviewRowsSpinner.setEnabled(false);
}
private void paintButton(Graphics2D g, JComponent c, int width, int height) {
boolean useToolBarColors = isInToolBar(c);
Shape s;
JSpinner spinner = (JSpinner) c.getParent();
boolean editorFocused = false;
JComponent editor = spinner.getEditor();
if (editor instanceof DefaultEditor) {
editorFocused = ((DefaultEditor)editor).getTextField().isFocusOwner();
}
if (focused || editorFocused) {
s = createButtonShape(0, 0, width, height, CornerSize.OUTER_FOCUS);
g.setPaint(getFocusPaint(s, FocusType.OUTER_FOCUS, useToolBarColors));
g.fill(s);
s = createButtonShape(0, 1, width - 1, height - 1, CornerSize.INNER_FOCUS);
g.setPaint(getFocusPaint(s, FocusType.INNER_FOCUS, useToolBarColors));
g.fill(s);
}
s = createButtonShape(0, 2, width - 2, height - 2, CornerSize.BORDER);
g.setPaint(getSpinnerNextBorderPaint(s, type));
g.fill(s);
s = createButtonShape(1, 3, width - 4, height - 4, CornerSize.INTERIOR);
g.setPaint(getSpinnerNextInteriorPaint(s, type));
g.fill(s);
}
/**
* Create an editable labelled spinner with provided
* characteristics.
*
* @param label the string to be used as label text
* @param tip the related tool tip text
*/
public LSpinner (String label,
String tip)
{
this.label = new JLabel(label, SwingConstants.RIGHT);
spinner = new JSpinner();
if (tip != null) {
this.label.setToolTipText(tip);
spinner.setToolTipText(tip);
}
}
public void setDate(Date date, boolean updateModel) {
Date oldDate = this.date;
this.date = date;
if (date == null) {
((JSpinner.DateEditor) getEditor()).getFormat().applyPattern("");
((JSpinner.DateEditor) getEditor()).getTextField().setText("");
} else if (updateModel) {
if (dateFormatString != null) {
((JSpinner.DateEditor) getEditor()).getFormat().applyPattern(
dateFormatString);
}
((SpinnerDateModel) getModel()).setValue(date);
}
firePropertyChange("date", oldDate, date);
}
/**
* @param property Integer property.
* @param minimum Minimum value.
* @param maximum Maximum value.
* @param stepSize Step size.
* @return JSpinner for the integer property.
*/
protected JSpinner createJSpinner(
ConfigurationValueInteger property,
int minimum, int maximum, int stepSize) {
if (property == null) {
return null;
}
Configuration config = Configuration.getConfiguration();
int value = config.getInt(null, property);
value = Math.max(minimum, Math.min(maximum, value));
SpinnerNumberModel model = new SpinnerNumberModel(value, minimum, maximum, stepSize);
JSpinner spin = new JSpinner(model);
integerValues.put(property, spin);
return spin;
}
/**
* Maps {@code JSpinner.getUI()} through queue
*/
public SpinnerUI getUI() {
return (runMapping(new MapAction<SpinnerUI>("getUI") {
@Override
public SpinnerUI map() {
return ((JSpinner) getSource()).getUI();
}
}));
}
private void setEditsAction(final Container con) {
if (con instanceof JSpinner)
return;
/*
* if(con instanceof JSplitPane){
* setEditsAction(((JSplitPane)con).getLeftComponent());
* setEditsAction(((JSplitPane)con).getRightComponent()); return; }
*/
for (int i = 0; i < con.getComponentCount(); i++) {
if (con.getComponent(i) instanceof Container)
setEditsAction((Container) con.getComponent(i));
final Component container = con.getComponent(i);
if (container instanceof JTextField) {
processTextField((JTextField) container);
} else if (container instanceof JPasswordField) {
((JPasswordField) container).addActionListener(listener);
}
if (container instanceof JTextComponent) {
addUndoFunctions((JTextComponent) container);
}
if (container instanceof JList
&& !(container instanceof JTableHeader)) {
((JList) container).addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(final MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1
&& e.getClickCount() > 1)
onOk();
}
});
}
}
}
public JExtendedSpinner(SpinnerModel model) {
super(model);
((JSpinner.DefaultEditor) getEditor()).getTextField().setFont(UIManager.getFont("Label.font")); // NOI18N
((JSpinner.DefaultEditor) getEditor()).getTextField().addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(final java.awt.event.KeyEvent e) {
if (e.getKeyCode() == java.awt.event.KeyEvent.VK_ESCAPE) {
processKeyEvent(e);
}
}
});
configureWheelListener();
}
@Override
protected void createComponents() {
super.createComponents();
{
final JLabel binCountLabel = new ResourceLabel("plotter.configuration_dialog.bin_count");
// create input text field
binCountSpinner = new JSpinner(new SpinnerNumberModel(5, 1, null, 1));
binCountLabel.setLabelFor(binCountSpinner);
binCountSpinner.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(final ChangeEvent e) {
binCountChanged();
}
});
addTwoComponentRow(this, binCountLabel, binCountSpinner);
}
final JPanel spacerPanel = new JPanel();
final GridBagConstraints itemConstraint = new GridBagConstraints();
itemConstraint.fill = GridBagConstraints.BOTH;
itemConstraint.weightx = 1;
itemConstraint.weighty = 1;
itemConstraint.gridwidth = GridBagConstraints.REMAINDER;
this.add(spacerPanel, itemConstraint);
}
private void releaseMouse(JSpinner jSpinner)
{
IntStream.range(0, jSpinner.getComponentCount())
.mapToObj(jSpinner::getComponent)
.filter(comp -> comp instanceof JButton)
.forEach(this::releaseMouse);
}
/**
* Creates new form NoiseSettingsEditor
*/
public NoiseSettingsEditor() {
initComponents();
JSpinner.NumberEditor scaleEditor = new JSpinner.NumberEditor(spinnerScale, "0");
scaleEditor.getTextField().setColumns(3);
spinnerScale.setEditor(scaleEditor);
}
static void createNumberSpinner() {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.YEAR, -1);
calendar.add(Calendar.YEAR, 1);
int currentYear = calendar.get(Calendar.YEAR);
SpinnerModel yearModel = new SpinnerNumberModel(currentYear, //initial value
currentYear - 1, //min
currentYear + 2, //max
1); //step
spinner = new JSpinner();
spinner.setModel(yearModel);
}
public void setModel(SpinnerModel model) {
Font font = ((JSpinner.DefaultEditor) getEditor()).getTextField().getFont();
String accessibleName = ((JSpinner.DefaultEditor) getEditor()).getTextField().getAccessibleContext().getAccessibleName();
String accessibleDescription = ((JSpinner.DefaultEditor) getEditor()).getTextField().getAccessibleContext()
.getAccessibleDescription();
super.setModel(model);
((JSpinner.DefaultEditor) getEditor()).getTextField().setFont(font);
((JSpinner.DefaultEditor) getEditor()).getTextField().getAccessibleContext().setAccessibleName(accessibleName);
((JSpinner.DefaultEditor) getEditor()).getTextField().getAccessibleContext()
.setAccessibleDescription(accessibleDescription);
}
@Override
public boolean checkComponent(Component comp) {
if (comp instanceof JSpinner) {
if (((JSpinner) comp).getValue() != null) {
return (comparator.equals(((JSpinner) comp).getValue().toString(),
label));
}
}
return false;
}
WidthHeightPanel(boolean showWidth, boolean showHeight) {
ResourceBundle bundle = NbBundle.getBundle(BoxFillerInitializer.class);
JLabel widthLabel = new JLabel(bundle.getString("BoxFillerInitializer.width")); // NOI18N
JLabel heightLabel = new JLabel(bundle.getString("BoxFillerInitializer.height")); // NOI18N
widthField = new JSpinner(new SpinnerNumberModel());
heightField = new JSpinner(new SpinnerNumberModel());
GroupLayout layout = new GroupLayout(this);
setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.TRAILING)
.addComponent(widthLabel)
.addComponent(heightLabel))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(widthField)
.addComponent(heightField))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(widthLabel)
.addComponent(widthField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(heightLabel)
.addComponent(heightField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
widthLabel.setVisible(showWidth);
heightLabel.setVisible(showHeight);
widthField.setVisible(showWidth);
heightField.setVisible(showHeight);
}