java - Is there any way to return from JFileChooser.showOpenDialog() programmatically? -
the context here unit testing: @ end of test, @ teardown, if jfilechooser left "hanging" (i.e. displayed), want force return "cancelled" value.
the problem that, otherwise, actionperformed() i've called showopendialog (a blocking method) continues live on... need close down runnable.
nb runnable running actionperformed of course running in edt. despite this, framework capable of starting "event pump": understanding quite normal , correct behaviour when jfilechooser.showopendialog in edt: similar functioning calling 1 of joptionpane.showxxx static methods in edt.
i want avoid "testing-contrived" solution this: in other words, application code must sufficient itself, , not use tortuous or unnatural mechanisms in knowledge going run testing code needs provide "handle".
ps using jython, rather java, , using python unittest module, rather java-based unit testing framework. doesn't change principles involved...
pps (later) have devised method regard rather "precarious": involves digging down jfilechooser identify jbutton gettext() == "cancel". sorry, it's written in jython, should pretty easy grasp know no python:
def close_main_frame(): self.main_frame.dispose() self.cancel_button = none def explore_descendant_comps( container, method, breadth_first = false, depth = 0 ): 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 ) , 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 ) this "precarious" not least because "cancel" text of button may replaced name in language...
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 ); } } using code, can call forcecancel() fires action event automatically cancel jfilechooser. can include forcecancel() in unit test.
( or )
if have component in jython call component.cancelselection() making instance of check on component.
Comments
Post a Comment