I don't know what is wrong, but it's very interesting. I made code with CardLayout
and panels. On panel with CardLayout
I put JButton
s from ArrayList
and it is working...
It's looking like this:
Panel with CardLayout
is on the bottom with pink JButton
s.....part of my code is
public class Controller extends JPanel {
ArrayList<JButton> tnp=new ArrayList<JButton>();
ArrayList<JButton> sokp=new ArrayList<JButton>();
ArrayList<JButton> alkp=new ArrayList<JButton>();
CardLayout cardlayout=new CardLayout();
JPanel cardpanel = new JPanel(cardlayout);
but, when I add static to ArrayList
like this:
static ArrayList<JButton> tnp=new ArrayList<JButton>();
static ArrayList<JButton> sokp=new ArrayList<JButton>();
static ArrayList<JButton> alkp=new ArrayList<JButton>();
my applicaton look like this:
As you can see, program still shows panel with CardLayout, (border with red
) but JButtons from
static ArrayList<JButton> tnp=new ArrayList<JButton>();
static ArrayList<JButton> sokp=new ArrayList<JButton>();
static ArrayList<JButton> alkp=new ArrayList<JButton>();
lost! why?
I don't unerstand. One ArrayList is for one panel with cardlayout, that panel is for all JTabbedPane, and I want to have access to that list from another class (that is why I want to be static), to add or remove buttons to that panel. But I can't, nothing adds to that arraylist .
A static field is a field that belongs to the class it's declared in. Whereas an instance (non-static) field belongs to an instance of the class it's declared in.
So, if you have the following:
public class Controller {
public static List<JButton> staticList = new ArrayList<JButton>();
public List<JButton> instanceList = new ArrayList<JButton>();
...
}
and the following user code:
Controller c1 = new Controller();
Controller c2 = new Controller();
each controller has its own instance list, but they both share a unique static list.
You want every controller to have its own buttons, so you definitely don't want static lists.
If you want to have access to a controller from another object, you simply need to pass the controller to this other class instance:
Controller c1 = new Controller();
OtherClass other = new OtherClass(c1);
And inside OtherClass
, you can do whatever you want with the controller:
private Controller theController;
public OtherClass(Controller controller) {
this.theController = theController;
}
public void foo() {
// call any method you want from theController
}