-2

I'm doing a project in java that uses a grille and put elements in it, i made a choice where the position in the grille (x,y) would be selected through a spinner but i ran to a problem where i need to set a max value for the spinners depends of what did the user made the dimensions of he grille so it would be changing the max value of the spinner through the code only. is there any function i can use or so?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433

1 Answers1

0

You can set the max value of a JSpinner using SpinnerNumberModel.setMaximum(). See below example.

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerNumberModel;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class SpinnerMax
{
  public static void main(String[] args)
  {
    SpinnerNumberModel model = new SpinnerNumberModel(20, 10, 50, 10);
    JSpinner spinner = new JSpinner(model);

    JButton button = new JButton("Set New Max Value");
    button.addActionListener(new ActionListener()
    {
      @Override
      public void actionPerformed(ActionEvent e)
      {
        model.setMaximum(70);
      }
    });

    JFrame f = new JFrame("Spinner");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().setLayout(new FlowLayout());
    f.getContentPane().add(new JLabel("Value:"));
    f.getContentPane().add(spinner);
    f.getContentPane().add(new JLabel("New Max Value:"));
    f.getContentPane().add(new JTextField(10));
    f.getContentPane().add(button);
    f.setBounds(300, 200, 400, 300);
    f.setVisible(true);
  }
}
Prasad Karunagoda
  • 2,048
  • 2
  • 12
  • 16