aspose file tools
The moose likes Beginning Java and the fly likes function scope? Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Beginning Java
Reply 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.
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: function scope?
 
Similar Threads
Swing simple
change back text of button with help of Thread.sleep()
change the texts to a different one in a JButton each time it is pressed.
programming style
Error !! in Swing