Accessing the components from another class

I am very new to java.

I have a class where i am creating gui and another class (main class), i am accessing the gui class. In the gui class i am creating some components and returning them.

gui class,

        public class Gui {

            public Component getTopPanelContent(){
                Jpanel jp = new Jpanel();
                JComboBox cbo1 = new JComboBox();
                JComboBox cbo2 = new JComboBox();
                JComboBox cbo3 = new JComboBox();
                JComboBox cbo4 = new JComboBox();
                JComboBox cbo5 = new JComboBox();
                JButton button = new JButton();

                return jp; 

main class,

        public void addComponents(int id){
           Gui g = new Gui();
           Jpanel container = new Jpanel();

           if(id == 1){

upto this its working fine.

In the main class there is a JTextArea, Whenever i open a file, i have to display the country list in cbo1, the file contains the list of countries that has to be displayed,

       String[] countries = editArea.getContents().split("\n");

How to pass the country values to cbo1



Well, i usually see a GUI class having the swing components as the class attributes. You made something like a 'util' class for your GUI, so you will have to hunt your JComboBox

I suggest you to go for a full featured class to represent you GUI, like:

import javax.swing.*;

public class Gui extends JPanel {

    private JComboBox cbo1 = new JComboBox();
    private JComboBox cbo2 = new JComboBox();
    private JComboBox cbo3 = new JComboBox();
    private JComboBox cbo4 = new JComboBox();
    private JComboBox cbo5 = new JComboBox();
    private JButton button = new JButton();

    public Gui() {

Also, add getters and setters ;-).

If you wanna keep your code your way, you can search the combobox by index:

System.out.println( jp.getComponent(0) );

Or, better, you can name your JComboBox and then search for it by name:


and then:

public Component findCbo1() {
    for (Component comp : this.getComponents()) {
        if(comp.getName() != null && comp.getName().equals("countryCombo")) {
            return comp;
    return null;

Need Your Help

Why is $value in this PHP foreach loop an array?

php jquery arrays foreach

In my jQuery code I'm creating an object like this:

Does a cookie's content become part of the request header always? cookies request-headers

The search application I am working on allows a user to select the results and export them in different formats like EXCEL, XML etc.