Yel*_* Il 3 java swing dispose window actionlistener
我正在学习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();
}
Run Code Online (Sandbox Code Playgroud)
当我点击我的时候,我希望那个窗口关闭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.");
}
}
}
Run Code Online (Sandbox Code Playgroud)
但是当我点击该按钮时,它会关闭我的主窗口,而不是我的子菜单窗口.我该怎么做才能解决问题?
您需要获得要关闭的窗口的引用,并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();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
267 次 |
| 最近记录: |