Scope in java | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Scope in java

I have created an action listener. When my button is clicked, the text in a jtextfield is assigned to an integer. Everything works fine. However when I try use the int numberOfPlayers outside the action listener it does not work. Pls help

20th Apr 2020, 3:46 PM
Stephen
1 Answer
0
Hello Stephen ok.addActionListener (new ActionListener () { @Override public void actionPerformed ( ActionEvent e ) { numberOfPlayers = Integer.parseInt (totalPlayerNumberField.getText ()); for(int i = 0; i < numberOfPlayers;i++){ playerName[i] = new JTextField(10); playerNameLabel[i] = new JLabel("Player " + i + "'s Name: "); System.out.println (playerName[i].getColumns ()); ok.setVisible (false); } } }); This construction is called anonymous class. You create a class and inside you override the method actionPerformed. You can use a variable created inside this method only inside this method. If you want to use it outside you have to create it outside.
20th Apr 2020, 4:41 PM
Denise Roßberg
Denise Roßberg - avatar