我目前正在学习Java
来提高自己。我有一个程序,它有一个主窗口、菜单和子菜单。
当我点击我的子菜单时,我有其他窗口。
其中之一是 setRates
public SetMyRates(){
JPanel dataPanel = new JPanel(new GridLayout(2, 2, 12, 6));
dataPanel.add(setTLLabel);
dataPanel.add(setDollarsLabel);
dataPanel.add(setTLField);
dataPanel.add(setDollarsField);
JPanel buttonPanel = new JPanel();
buttonPanel.add(closeButton);
buttonPanel.add(setTLButton);
buttonPanel.add(setDollarsButton);
Container container = this.getContentPane();
container.add(dataPanel, BorderLayout.CENTER);
container.add(buttonPanel, BorderLayout.SOUTH);
setTLButton.addActionListener(new SetTL());
setDollarsButton.addActionListener(new SetDollars());
closeButton.addActionListener(new closeFrame());
dataPanel.setVisible(true);
pack();
}
我希望在我点击 closeButton
时关闭该窗口。
我为 closeButton 创建了一个类,actionListener 是:
private class closeFrame implements ActionListener{
public void actionPerformed(ActionEvent e){
try{
dispose();
}
catch(Exception ex){
JOptionPane.showMessageDialog(null, "Please enter correct Rate.");
}
}
}
但是当我单击该按钮时,它会关闭我的主窗口而不是子菜单窗口。我到底应该怎么做才能解决这个问题?
最佳答案
您需要获取对要关闭的窗口的引用,并直接对该引用调用 dispose()
。您如何执行此操作将取决于您的计划的详细信息——我们目前不了解的信息。
编辑:获取该引用的一种方法是通过 SwingUtilities.getWindowAncestor(...)
。传入从 ActionEvent 对象返回的 JButton 引用并对其调用 dispose。像...
public void actionPerformed(ActionEvent e) {
Object o = e.getSource();
if (o instanceof JComponent) {
JComponent component = (JComponent)o;
Window win = SwingUtilities.getWindowAncestor(component);
win.dispose();
}
}
- 警告:代码既没有以任何方式编译、运行也没有经过测试。
- 另请注意,要使其正常工作,保存并激活 ActionListener 的组件必须驻留在您希望关闭的窗口上,否则将无法正常工作。
关于java - 使用按钮关闭窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10462307/