簡體   English   中英

用按鈕關閉窗口

[英]Closing a Window with Button

我目前正在學習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.");
       }
    }
}

但是,當我單擊該按鈕時,它將關閉我的主窗口而不是子菜單窗口。 我應該怎么做才能解決該問題?

您需要獲取要關閉的Window的引用,然后直接對該引用調用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的組件必須駐留在您希望關閉的Window上,否則將無法正常工作。

根據我的想法,打開另一個窗口時,您可以輕松地存儲對它的引用,並在動作監聽器中使用它。 遵循以下原則:

JFrame openedWindow;

//inside the listener
if(openedWindow)
   openedWindow.dispose();
else dispose();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM