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
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.