问题描述:

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.

网友答案:

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.

网友答案:

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;
  }      

}
相关阅读:
Top