-
How to pass object reference to actionPerformed
Hello,
I could not find a way to reach reference of my object in actionPerformed method. Please help me!
I was trying to create an application like a registration page. It has several Jbuttons, labels, checkboxes, radio buttons etc. When the user selects and presses the submit button, I want to display the information in a textArea.
I created a class called "User" to store and manipulate some data (with get and set methods)
Other class "mainFrame" extends the JFrame. In the constructor of this class, I created a new user by User user = new User().
However, when I tried to reach the reference of this object from ActionPerformed method, it returns null. Here is the sample code.
class User {
int salary,
String zip;
...
set();
get();
calculate();
}
MainFrame extends JFrame implements ActionListener {
private JLabel;
..........
MainFrame
{
User user = new User();
. ..
. .
..}
public void actionPerformed( ActionEvent event) {
if ( event.getSource() == submit )
{
System.out.println(user); //this RETURNS NULL
}
Thanks a lot in advance
-
You can't
If you in your MainFrame class want to refer an object then that objects
scope must cover the method(s) where you want to reference the object.
So in your MainFrame class you should do like:
Code:
MainFrame extends JFrame implements ActionListener {
private JLabel;
// define the object
User user=null; // this user can be referenced by all the methods in MainFrame
public MainFrame () {
user = new User(); // now create the object
. ..
. .
..}
public void actionPerformed( ActionEvent event) {
if ( event.getSource() == submit ) {
System.out.println(user); // not null anymore
}
}
PS: The actionPerformed(ActionEvent e) method is defined by the
ActionListener interface, and the only parameter is the ActionEvent. If
you add another parameter then the method signature (its name and
its parameter types and sequence) is not the ActionListener interface
implementation. You will get a compile error telling you that you haven't
implemented the interface.
eschew obfuscation
-
Thank you very much.
-
hey If you need to access the values in textboxes then create instances of textbox in the class where you are implementing actionlistener. Then you can refer to the value stored some thing like this
JTextBox temp= new JTextBox();
.........
.........
........
here is your actionlistener
{
String c= temp.getText();// this will give you values entered in text box
here replace c by the variable you want.
}
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
Forum Rules
|
Top DevX Stories
Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL
|
Bookmarks