Issue
I am building a little Java Swing Program with the NetBeans IDE and GUI Builder. I´ve made a little JFrame with a textfield and a button on it. The User can insert a number and can confirm that number by hitting enter or press the jbutton below.
private void plySetterBtnActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if(evt.getSource() == plySetterBtn) {
int numberOfPlayers = 0;
try{
numberOfPlayers = Integer.parseInt(this.playerNumberField.getText());
dispose();
} catch(Exception e) {
JOptionPane.showMessageDialog(this, "Please insert only numeric digits (0-9) \n Note: Spaces will be counted as letters.", "Error#094:", JOptionPane.ERROR_MESSAGE);
}
}
}
I wanted to use the int "numberOfPlayers" outside this private method by using a getter and setter, but this is where I stuck. (As I just said the Code is partially generated by the NetBeans GUI Builder.) When I try to setup a setter and getter inside the Code above the IDE says "illegal start of expression"
When I try to setup the setter and getter out of this Code the IDE says that the int "numberOfPlayers" does not exist.
What do I do wrong and what could I different?
Solution
I think a better way is to make a public method that returns the value you want, something like this:
public class MyFrame extends JFrame implements PlayerGui {
// ...etc.
public int getPlayerNumber() {
return Integer.parseInt(this.playerNumberField.getText());
}
}
You may need to press the "Source" button on the GUI editor so you can just add the arbitrary source code you want. Then you call this method externally to your class. It also helps to make an interface so you can more easily mock and inject test classes into the rest of your code.
public interface PlayerGui {
int getPlayerNumber();
}
Answered By - markspace
Answer Checked By - Pedro (JavaFixing Volunteer)