Reputation: 259
In Java, I have 2 classes. One contains a JFrame. On startup, that class is called. The JFrame shows.
But in the other class, when I press a button on it's own frame, it opens a new instance of that class which should make another frame. But it just focuses on the old frame already opened...
Source:
FrameToOpen.java
public FrameToOpen() {
JFrame frame = new JFrame();
// Just the most simple settings to make it appear...
frame.setSize(400, 200);
frame.setVisible(true);
}
OtherClass.java
public OtherClass() {
JFrame frame = new JFrame();
JPanel window = new JPanel();
JButton openFrame = new JButton("Open Frame);
// Again, just the most simple settings to make it appear with components...
frame.setSize(400, 200);
frame.setVisible(true);
frame.add(window);
window.setLayout(null);
window.add(openFrame);
openFrame.setBounds(5, 5, 100, 30);
openFrame.addActionListener(this);
frame.repaint();
frame.validate();
}
public void actionPerformed(ActionEvent e) {
Object o = e.getSource();
if (o == openFrame) {
// THIS HERE MAKES NEW INSTANCE OF FRAMETOOPEN
new FrameToOpen();
}
}
So, when I press this button, it doesn't open a new frame, but just focuses on old one.
Please help.
'Actual' Classes
ServerGUI.java
if (o == openAdmin) {
int port;
try {
port = Integer.parseInt(portNumber.getText().trim());
} catch(Exception er) {
appendEvent("Invalid Port Number.");
return;
}
// FrameToOpen.java. Opening a new instance of that class...
new ClientGUI("localhost", port, true);
}
ClientGUI.java
static JFrame frame = new JFrame("Chat Client");
Dimension d = new Dimension(600, 600);
JMenuBar menu = new JMenuBar();
public ClientGUI(String host, int port, boolean isHost) {
this.isHost = isHost;
frame.setSize(d);
frame.setMinimumSize(d);
//frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setJMenuBar(menu);
frame.setVisible(true);
// Everything else in the class is my buttons, lists, editor panes,
// and socket handling...
}
Upvotes: 2
Views: 2218
Reputation: 29680
You defined your frame variable as being static
:
static JFrame frame = new JFrame("Chat Client");
so it is created only once for the class, no matter how many instances are created. Remove the static
modifier if you want to hava it as an instance field.
Upvotes: 4