swing - Tips to Keep a Responsive User Interface in Java -


what best way keep buttons , others components in swing responsive. use "new thread(){public void run(){}}.start();" on every action listener don't know how stop or cancel thread without using "thread.stop()" suggestions or tips?

my rule of thumb start thread if it's very long running task. , long running mean practically same life of application. therefore never start own threads.

starting thread each little operation bad idea because threads expensive spin up. usual solution use threadpool reuse threads , take headache away you.

but it's swing, there option of swingworker run on background pooled thread , give easy way update ui results in correct thread.

from https://docs.oracle.com/javase/8/docs/api/javax/swing/swingworker.html

final jlabel label; class meaningoflifefinder extends swingworker<string, object> {     @override    public string doinbackground() {        return findthemeaningoflife();    }      @override    protected void done() {        try {            label.settext(get());        } catch (exception ignore) {        }    } }  swingworker<string, object> worker = new meaningoflifefinder(); worker.execute(); 

cancelling

see https://docs.oracle.com/javase/tutorial/uiswing/concurrency/cancel.html

cancelling swing worker easy. worker.cancel(false); sets flag must checking iscancelled().

@override public string doinbackground() {    //somework    if(iscancelled()) return ...; // check , return when cancelled    //somemorework     return ...; } 

Comments

Popular posts from this blog

Fail to load namespace Spring Security http://www.springframework.org/security/tags -

sql - MySQL query optimization using coalesce -

unity3d - Unity local avoidance in user created world -