java jframe案例,一个JFrame的多个实例

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...

}

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值