wood burning stoves 2.0*
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 OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "function scope?" Watch "function scope?" New topic
Author

function scope?

Shane Thornton
Greenhorn

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();
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

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.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: function scope?