[Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 301
  • Last Modified:

Reference a object from another method in Java

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

0
Mannsi
Asked:
Mannsi
  • 6
  • 4
  • 4
  • +2
2 Solutions
 
CEHJCommented:
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
0
 
MannsiAuthor Commented:
Yes, it's a JFrame.

I'm new to Java, could you maybe give me a simple example ?
0
 
CEHJCommented:
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
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
MannsiAuthor 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.
0
 
CEHJCommented:
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
0
 
MannsiAuthor 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 ?
0
 
beekeepCommented:
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.
0
 
fsze88Commented:
private JPanel panelCenter = new JPanel ();
this.getContentPane().add( panelCenter, BorderLayout.CENTER);
JFrame jf = (JFrame)panelCenter.getTopLevelAncestor();
System.out.println("jf.getName() : " + jf.getName());
0
 
objectsCommented:
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());
            ...
        }

0
 
CEHJCommented:
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
0
 
MannsiAuthor 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.
0
 
objectsCommented:
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);
         }
}
0
 
CEHJCommented:
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

0
 
objectsCommented:
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);
         }
}

0
 
objectsCommented:
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);
      }
}
0
 
CEHJCommented:
:-)
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 6
  • 4
  • 4
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now