I have an array of Strings and i want to print the Strings in Jframes. I use a for to call another class wich will create a Jframe with a Jpanel. It goes something like this:

for(int i=0;i!=v.length;i++){  
  (...)
  NewWindow wind = new NewWindow();
}

The problem is when i want to close one of those Jframes. I know the title/window name but i lost the pointer because wind is only valid for the last Jframe created.

I don't know another way to create an unknown number of Jframes, without loosing the pointer, or to get focus of the Jframe. Is it possible in java?

有帮助吗?

解决方案

Why not just keep your references to the windows?

NewWindow[] windows = new NewWindow[v.length];
for (int i = 0; i < v.length; i++) {
    // (...)
    windows[i] = new NewWindow();
}

Or, alternatively:

ArrayList<NewWindow> windows = new ArrayList<NewWindow>(v.length);
for (int i = 0; i < v.length; i++) {
    // (...)
    windows.add(new NewWindow());
}

EDIT: Or as per skirsch's answer, if you want to be able to access the windows by the value of the string, use a Map<String, NewWindow>

其他提示

One could argue against your GUI design of displaying multiple JFrames (and believe me, I do have some significant issue with this), but putting that aside for now, the basic issue you have is that you're trying to use a single reference variable to refer to a bunch of objects. The solution is to not use one reference to a single JFrame, but instead use an ArrayList<JFrame> or other collection to refer to multiple objects. When creating and displaying the JFrame, put it in the collection, and then of course be sure to remove the object from the collection when it is removed from view.

You may use a Map to keep the references. E.g. define

Map<String,NewWindow> windows = new HashMap<String,NewWindow>();
for (int i=0; i != v.length; i++) {
  NewWindow wind = new NewWindow();
  windows.put(v[i], wind);
}

And later on get a reference to the window with something like that

String titleName = ...
NewWindow wind = windows.get(titleName);
// close window

But seriously... how many windows will you open?

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top