Reputation: 13
Hi I am currently working on an assignment which I have 98% finished. I have made gui program where it has a jtextfield set to 0 but as you play the game it changes.
Now I have created a j button called "NEW GAME" and "QUIT". My Quit button works fine when clicked. but my new game button is my problem.
I want it so that when I click the button it sets the score to 0
public ShinyButtonsGUIProgramToShare(String tit, int x, int y) {
//The button GUI
ShinyButtonsGUIToShare sbg = new ShinyButtonsGUIToShare("NYI", 552, 552, new ShinyButtons());
sbg.setLocation(10, 10);
getContentPane().add(sbg);
//The score text and text box
JLabel jlb = new JLabel("Score: ");
jlb.setLocation(12, (y - 75));
jlb.setSize(45, 40);
getContentPane().add(jlb);
JTextField jtf = new JTextField("0");
jtf.setLocation(60, (y - 70));
jtf.setSize(150, 30);
jtf.setHorizontalAlignment(JTextField.RIGHT);
getContentPane().add(jtf);
JButton NewGame, Quit;
NewGame = new JButton("New Game");
Quit = new JButton("Quit");
Quit.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
System.exit(0);
}});
NewGame.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
JTextField jtf.setText("0");
}});
NewGame.setLocation((x - 220), (y - 70));
NewGame.setSize(100, 30);
getContentPane().add(NewGame);
Quit.setLocation((x - 110), (y - 70));
Quit.setSize(100, 30);
getContentPane().add(Quit);
setDefaultCloseOperation(EXIT_ON_CLOSE); // allow window to close
setSize(x, y);
setLayout(null);
setResizable(false);
}
public static void main(String[] args) {
ShinyButtonsGUIProgramToShare sbgp = new ShinyButtonsGUIProgramToShare("Shiny Buttons", 578, 634);
sbgp.setVisible(true);
}
}
Upvotes: 0
Views: 205
Reputation: 347244
You have a context issue...
The instance of jtf
can not be referenced from within the context of the NewGame
's ActionListener
You need to make jtf
and instance variable so it can be accessed from anywhere within an instance of ShinyButtonsGUIProgramToShare
object.
Take a look at Understanding Class Members and Code Conventions for the Java Programming Language
Upvotes: 1