问题描述
在Java中,我有2个类.一个包含一个JFrame.在启动时,将调用该类.显示JFrame.
In Java, I have 2 classes. One contains a JFrame. On startup, that class is called. The JFrame shows.
但是在另一个类中,当我在其自己的框架上按下按钮时,它将打开该类的 new 实例,该实例应该构成另一个框架.但这只是针对已经打开的旧框架...
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...
来源:
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.
请帮助.
实际"课程
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...
}
推荐答案
您将框架变量定义为static
:
static JFrame frame = new JFrame("Chat Client");
因此,无论创建了多少实例,该类仅为该类创建一次.如果您想将static
修饰符用作实例字段,请删除它.
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.
这篇关于一个JFrame的多个实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!