-2

So I have bunch of grids on my window and I have a JTextField, I want to write a number, say

20, in the text field and the 20 would change my grid size to 20 and so on.

Here you see I have set it to 30, I can set it to any number, but like I said I want to be

able to change/set the number when I type it in the text field after I run the program.

This is my Grids class and not the main class, In my main class I created the text field and

such. Also I have my actionPreformed in my main so what do I need in my actionPreformed

(if necessary)?

So my question is after running the program how to write in the text field a

number (10,20,30 any number) and be able to change my grid size based on the number I typed?

Also what do I need in my actionPreformed (if necessary)?

Grids class:

protected int gridSize = 30; // how many grids
public Grids( ghetto ttt  )
{
   setLayout( new GridLayout( gridSize, gridSize ) );
   theSquares = new Marker[gridSize][gridSize];
   for ( int i=0; i<gridSize; i++ )
   {
       for ( int j=0; j<gridSize; j++ )
       {
           theSquares[i][j] = new Marker(gridSize , this );
           add(theSquares[i][j]);
       }
   }

}
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720

2 Answers2

2

I would use a JSpinner with a ChangeListener.

Read the section from the Swing tutorial on How to Use Spinners for more information and examples.

camickr
  • 321,443
  • 19
  • 166
  • 288
1

So an actionlistener probably won't work. That condenses click events into ActionEvents. What you can do is add a document listener. See Value Change Listener to JTextField.

In your main program where you would do

    textField.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            // Whatever
        }
    });

you do

 textField.getDocument().addDocumentListener(new DocumentListener() {
        @Override
        public void removeUpdate(DocumentEvent arg0) {
            //whatever
        }
        @Override
        public void insertUpdate(DocumentEvent arg0) {
            //whatever
        }
        @Override
        public void changedUpdate(DocumentEvent arg0) {
            //whatever
        }
    });
Community
  • 1
  • 1
k_g
  • 4,333
  • 2
  • 25
  • 40