We help IT Professionals succeed at work.

Reference a object from another method in Java

Mannsi
Mannsi asked
on
Medium Priority
333 Views
Last Modified: 2012-05-06
Hello experts,

I'm having some java problems. I've created a program that starts with a call to CreateGUI() from main. CreateGUI() creates a frame and a couple of panels that I add some buttons on to. When one of the buttons is pressed some data is read from a file and added to a array. I than need to edit the GUI based on the data read, but I don't know to reference to the panels that where created in the CreateGUI() method. How can I accomplish this ?

I've added the code hierarchy below. Please ask if I've not made somethings clear.

I don't really need to use the setup as described below. If my problem can be solved by completely altering things, I'm all for it.

Thanks
public class Panel_class
{
	public static void main (String[] args)
	{
		CreateGUI();
	}
 
        public static void load_array(String s)
        {
              //loads the array from input file
              //HERE I WOULD LIKE TO EDIT THE PANELS IN CREATEGUI()
        }
 
        public static class ButtonListener1 implements ActionListener
        {
             //Listens for the button click
        }
 
       	 public static void CreateGUI()
         {
              //Creates the GUI based on the description above         
         }
}

Open in new window

Comment
Watch Question

CERTIFIED EXPERT
Top Expert 2016

Commented:
You need accessor (get) method in the gui that you create. CreateGUI should probably not be a void method but return the main container (JFrame?) that gets created. You need get method in that container for what you want to access

Author

Commented:
Yes, it's a JFrame.

I'm new to Java, could you maybe give me a simple example ?
CERTIFIED EXPERT
Top Expert 2016

Commented:
You need to read up on creating frames. Try starting here and look at the examples they give:

http://java.sun.com/docs/books/tutorial/uiswing/components/frame.html

Author

Commented:
I changed to CreateGUI() method so that it returned a JFrame object. I then talked to a friend of mine who advised me to set the returned JFrame as a global variable, and that seems to work. I'm gonna give you a few minutes to criticize this solution (e.g. if it's not good practice or something) before I award the points.
CERTIFIED EXPERT
Top Expert 2016

Commented:
Generally speaking, you should rarely write static methods (apart from main) unless they are in a utility library or you have some special reason.

Similarly, global variables should be avoided if possible
CERTIFIED EXPERT

Commented:

Author

Commented:
hmmm...

Change of status. After I changed CreateGUI from void to JFrame (returning myFrame) and declared myFrame as a global variable I was able to change the title of myFrame from the load_array method. However, I can't seem to add another panel to it.

fsze88: I'm a java retard, where and how should I use these methods ?

Commented:
Other commenters are quite correct that it is considered bad form to have large numbers of static (global) variables.  What *would* be considered good form would be to create a new class to represent your GUI and have createGUI return that.  Any or all of the components of the gui would be stored in fields of this class.  If you wanted a quick-and-dirty solution, you could make those fields public so that you could manipulate it directly.  Even better would be to keep the fields private but add appropriate manipulation fields to the GUI class.  For example, if your array were a bunch of customer names to be shown in a list, you'd include an "addCustomers" method to the class.
CERTIFIED EXPERT

Commented:
private JPanel panelCenter = new JPanel ();
this.getContentPane().add( panelCenter, BorderLayout.CENTER);
JFrame jf = (JFrame)panelCenter.getTopLevelAncestor();
System.out.println("jf.getName() : " + jf.getName());
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
Returning your JFrame generally is not that useful and just complicates things.
beekeep's suggestion is good to create a new class, and have your firelds that you need access to as a member.
I'd suggest subclassing JPanel for this purpoee like this:

public class MyPanel extends JPanel
{
   // field member vars
   private JButtom button;

   public MyPanel()
   {
       // initialise your gui here
   }

        public static void main (String[] args)
        {
            JFrame frame = new JFrame();
            frame.add(new MyPanel());
            ...
        }

CERTIFIED EXPERT
Top Expert 2016

Commented:
There's no need to create a new class really. The class that represents the gui might just as well be the JFrame itself or a subclass thereof. It really depends on what you want to do with it.

Don't stack up code in your main method and create GUI components like that. See Sun's recommended way of handling initialisation in examples such as:

http://java.sun.com/docs/books/tutorial/uiswing/examples/components/FrameDemoProject/src/components/FrameDemo.java

Author

Commented:
Ok.
Given the example that you pointed out CEHJ, how should I change that code so that I could edit the variable frame that gets created in 'private static void createAndShowGUI()' when I'm in another method ?
I don't quite understand the getters and setters thing.
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
public class Panel_class extends JPanel
{
      // add the compoents you need here as member variables

        public static void main (String[] args)
        {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                CreateGUI();
            }
        });
        }
 
        public static void load_array(String s)
        {
              //loads the array from input file
              //HERE I WOULD LIKE TO EDIT THE PANELS IN CREATEGUI()
        }
 
        public static class ButtonListener1 implements ActionListener
        {
             //Listens for the button click
        }
 
         public static void CreateGUI()
         {
        JFrame frame = new JFrame("FrameDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


JPanel panel = new Panel_class();
frame.getContentPane().add(panel);

// add your components to panel here
// make them member vars so you can access from other methods

        //Display the window.
        frame.pack();
        frame.setVisible(true);
         }
}
CERTIFIED EXPERT
Top Expert 2016
Commented:
You need to create a class and use an instance variable. Your could use your Panel class as a private class like this:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
 
 
public class F extends JFrame {
 
    private void setGui() {
	try {
	    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
	    Container cp = getContentPane();
	    cp.add(new YourPanel());
	} catch (Exception e) {
	    e.printStackTrace();
	}
    }
 
    public static void main(String[] args) {
	try {
	    SwingUtilities.invokeAndWait(new Runnable() {
		public void run() {
		    F f = new F();
		    f.setGui();
		    f.setSize(200, 200);
		    f.setVisible(true);
		}
	    });
	} catch (Exception e) {
	    e.printStackTrace();
	}
    }
 
 
    private class YourPanel extends JPanel {
	public YourPanel() {
	    add(new JLabel("Example"));
	}
    }
}

Open in new window

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
you can get rid of those statics with what i suggesated above

public class Panel_class extends JPanel
{
      // add the compoents you need here as member variables

        public static void main (String[] args)
        {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                CreateGUI();
            }
        });
        }
 
        public void load_array(String s)
        {
              //loads the array from input file
              //HERE I WOULD LIKE TO EDIT THE PANELS IN CREATEGUI()
        }
 
        public class ButtonListener1 implements ActionListener
        {
             //Listens for the button click
        }
 
         public static void CreateGUI()
         {
        JFrame frame = new JFrame("FrameDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


JPanel panel = new Panel_class();
frame.getContentPane().add(panel);

// add your components to panel here
// make them member vars so you can access from other methods

        //Display the window.
        frame.pack();
        frame.setVisible(true);
         }
}

Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010
Commented:
following should give u an idea what I mean. shows you how u can access your components

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class MyPanel extends JPanel {
      // add the compoents you need here as member variables

      private JLabel label = new JLabel();
      
      public static void main(String[] args) {
            // Schedule a job for the event-dispatching thread:
            // creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                  public void run() {
                        CreateGUI();
                  }
            });
      }

      public MyPanel()
      {
            JButton button = new JButton("Test");
            button.addActionListener(new ButtonListener1());
            add(label);
            add(button);
      }
      public void load_array(String s) {
            // HERE I WOULD LIKE TO EDIT THE PANELS IN CREATEGUI()
            label.setText(s);
      }

      public class ButtonListener1 implements ActionListener {

            public void actionPerformed(ActionEvent e) {
                  label.setText("Pressed");
            }
      }

      public static void CreateGUI() {
            JFrame frame = new JFrame("FrameDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            MyPanel panel = new MyPanel();
            panel.load_array("23");
            frame.getContentPane().add(panel);

            // Display the window.
            frame.pack();
            frame.setVisible(true);
      }
}
CERTIFIED EXPERT
Top Expert 2016

Commented:
:-)
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.