0

so i'm trying to access the JComboBox from the class called Calculator. the JComboBox itself lies in a method, and inside a JPanel in another class called GUI. thanks.

here's my code

public class GUI {
public static JFrame MainFrame(){

//the endless code

frame.add(konvpanel();

return frame;

}

public static JPanel konvpanel(){
    JPanel a = new JPanel();

String [] itembox = {"...","XXX","===","|||"};
        JComboBox nnn = new JComboBox(itembox);

a.add(nnn);

return a;
  }
}

thanks in advance.

2 Answers 2

2

You can't access nnn since that reference doesn't exist outside the scope of that method. So you have two options:

  • put a reference to the combox elsewhere, e.g. as an instance variable or (ouch) static variable
  • try and locate the panel within the frame and the combobox within the panel (e.g. by getting all children and checking their types and position).

I'd go with option one.

Another option, depending on why you need to access the combo box, might be to add a listener to the combo box and add a reference to the Calculator instance to that listener as well. Then whenever the event you registered for is triggered, you pass that information to the calculator.

Sign up to request clarification or add additional context in comments.

Comments

0

In your case to access the JComboBox, declare it as below.

public class GUI {
  public static JComboBox nnn;
  public static JPanel konvpanel(){
     JPanel a = new JPanel();

    String [] itembox = {"...","XXX","===","|||"};
    nnn = new JComboBox(itembox); /*refer the previously declared variable*/

    a.add(nnn);

   return a;
  }      

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.