簡體   English   中英

有什么方法可以通過編程從JFileChooser.showOpenDialog()返回嗎?

[英]Is there any way to return from JFileChooser.showOpenDialog() programmatically?

這里的上下文是單元測試:在測試結束時,在tearDown ,如果JFileChooser處於“掛起”狀態(即顯示),我想強制其返回“ Cancelled”值。

問題在於,否則,我稱為showOpenDialog (阻塞方法)的actionPerformed() )繼續存在……我需要關閉該Runnable

注意, Runnable運行actionPerformed當然是在EDT中運行的。 但是盡管如此,該框架還是能夠啟動另一個“事件泵”:我的理解是,在EDT中執行JFileChooser.showOpenDialog時,這是非常正常且正確的行為:類似於調用JOptionPane.showXXX靜態方法之一的功能。在EDT中。

我還想避免針對此問題的“測試人為”解決方案:換句話說,應用程序代碼本身必須足夠,並且不要使用曲折或不自然的機制,因為它將通過測試代碼來運行它需要提供一個“句柄”。

PS我實際上使用的是Jython,而不是Java,並且我使用的是Python unittest模塊,而不是基於Java的單元測試框架。 但這並不會改變所涉及的原則...

PPS (后來)我設計了一種我認為相當“不穩定”的方法:這涉及挖掘JFileChooser以使用getText() ==“ Cancel”標識JButton 抱歉,它是用Jython編寫的,但是即使對於不懂Python的人也應該很容易理解:

def close_main_frame():
    self.main_frame.dispose()
    self.cancel_button = None
    def explore_descendant_comps( container, method, breadth_first = False, depth = 0 ):
        for component in container.components:
            if isinstance( component, java.awt.Container ):
                if breadth_first:
                    method( component, depth )
                explore_descendant_comps( component, method, breadth_first, depth + 1 )
                if not breadth_first:
                    method( component, depth )
    def identify_cancel_button( comp, depth ):
        if isinstance( comp, javax.swing.JButton ) and comp.text == 'Cancel': 
            self.cancel_button = comp
    explore_descendant_comps( self.main_frame.analysis_file_chooser, identify_cancel_button )
    if self.cancel_button:
        self.cancel_button.doClick()
    else:
        raise Exception()

self.edt_despatcher.run_in_edt( close_main_frame, False ) 

這是“不穩定的”,尤其是因為按鈕的“取消”文本可能會被其他語言的其他名稱替換...

JFileChooser chooser = new JFileChooser();
chooser.addActionListener( new ActionListener() 
{
    public void actionPerformed(ActionEvent e) 
    {
       if( e.getActionCommand().equals("CancelSelection") )
       {
            chooser.cancelSelection();
       }
    }
} );

public void forceCancel()
{
   ActionEvent e = new ActionEvent(chooser, ActionEvent.ACTION_PERFORMED, "CancelSelection");
   fireActionPerformed(e);
}

public void fireActionPerformed( ActionEvent e )
{
   ActionListener[] listeners = chooser.getActionListeners();
  for( ActionListener listener : listeners )
  {
     listener.actionPerformed( e );
  }
}

使用此代碼,您可以調用forceCancel() ,它會觸發操作事件以自動取消JFileChooser 您可以在您的單元測試中包括forceCancel()

( 要么 )

如果您的Jython中有組件,則通過對組件進行檢查的實例來調用component.cancelSelection()。

暫無
暫無

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

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