Only 44 hours left in the trailboss' kickstarter!

New rewards and stretch goals. CLICK HERE!



Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

function scope?  RSS feed

 
Shane Thornton
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here is my code that doesn't seem to work.

import javax.swing.*;
import java.awt.event.*;

public class SimpleGUI implements ActionListener
{
public static void main(String[] args){
SimpleGUI gui = new SimpleGUI();
gui.go();
}
public void go(){
JFrame frame = new JFrame();
JButton button = new JButton("Submit");
button.addActionListener(this);

frame.getContentPane().add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent event){
button.setText("Whoa, I've changed!");
}
}

Please run that yourself. It seems that the OBJECT button is out of scope from the actionPerformed function... Any ideas how I can fix this?
 
Ken Blair
Ranch Hand
Posts: 1078
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, it is out of scope. You have declared button as a local variable, it will only be visible within that method. One way of fixing your code is to make the button a field of SimpleGUI.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!