It's not a secret anymore!
The moose likes Swing / AWT / SWT and the fly likes Access an Object from another file [Swing GUI] Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Reply Bookmark "Access an Object from another file [Swing GUI]" Watch "Access an Object from another file [Swing GUI]" New topic
Author

Access an Object from another file [Swing GUI]

Steffen Lima
Greenhorn

Joined: Feb 14, 2013
Posts: 2
Hi all,

got a very simple question which I currently have no idea how to solve (thats why I'm posting it now

I build an action listener for a button, but I used a separate file for this (class MiniGuiActionListener). So far so good. But now, when the button was clicked, I want to access the jButton object from within the actionPerformed method. How can I accomplish this? (I just want to invoke something like jButton.setText(...) ).

Thanks in advance,
Steffen

I got these two simple Java files (with all imports etc.):


Second file:



Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 32611
    
    4
Welcome to the Ranch
I shall move this discussion to our GUIs forum.
If the button is a local variable in that method, it ceases to exist outside the method, unless you pass a reference to it elsewhere. Why not pass a reference to the constructor of the listener class, and keep it as a field of the listener class? Then you can access it inside the listener class.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 32611
    
    4
I see it is a field. You ought to have given it private access. You can pass it as an argument to eht Listener class’s constructor just the same as for a local variable.
Steffen Lima
Greenhorn

Joined: Feb 14, 2013
Posts: 2
Perfect - passing an object reference to the constructor just solved my little "problem"

Thank you very much !!
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 32611
    
    4
You’re welcome
 
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: Access an Object from another file [Swing GUI]
 
Similar Threads
where to define my menubar
Help with assignment and JFileChooser
function scope?
change the texts to a different one in a JButton each time it is pressed.
Help with a simple gui