File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes function scope? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "function scope?" Watch "function scope?" New topic

function scope?

Shane Thornton

Joined: Jun 01, 2006
Posts: 3
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();
public void go(){
JFrame frame = new JFrame();
JButton button = new JButton("Submit");

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

Joined: Jul 15, 2003
Posts: 1078
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.
I agree. Here's the link:
subject: function scope?
It's not a secret anymore!