java - What is the prefered method for opening starting a swing interface and what's difference? -
this question has answer here:
so i've found multiple ways of implementing swing gui in java don't know each , teacher isn't able me. 1 method of creating jframe is:
import javax.swing.*; import java.awt.*; public class ui extends jframe{ public ui() { initalisegui(); } private void initalisegui(){ settitle("my title"); setbackground(color.red); setsize(800,500); setlocationrelativeto(null); setdefaultcloseoperation(exit_on_close); } public static void main(string[] args){ eventqueue.invokelater(new runnable(){ @override public void run(){ ui m = new ui(); m.setvisible(true); } }); }
but way of implementing is:
import javax.swing.*; import java.awt.*; public class main{ public static void main(string[] args){ jframe window = new jframe(); window.setsize(500,500); window.setdefaultcloseoperation(jframe.exit_on_close); container c = window.getcontentpane(); c.setbackground(color.red); window.setbackground(color.red); window.settitle("main"); jlabel message = new jlabel("jlabel"); window.add(message); window.setvisible(true); } }
what difference between how each 1 works , when should use 1 on other , how runnable work in context?
thankyou!
your first example calls eventqueue invokelater method, extends jframe.
your second example puts in static method main, , doesn't run invokelater method.
here's 1 way start swing application.
public class tryingproject2 implements runnable { public static void main(string[] args) { swingutilities.invokelater(new tryingproject2()); } @override public void run() { jframe frame = new jframe("color gradient test"); frame.setdefaultcloseoperation(jframe.exit_on_close); frame.add(createmainpanel()); frame.pack(); frame.setlocationbyplatform(true); frame.setvisible(true); } private jpanel createmainpanel() { jpanel panel = new jpanel(); // add swing components here return panel; } }
i don't extends swing components. use swing components. time extend swing component, or java class, when want override 1 of class methods.
the swingutilities invokelater method same eventqueue invokelater method. method puts creation , updates of swing components on event dispatch thread.
i implement runnable because makes invokelater method parameter instance of class.
i create main panel in method keep jframe code separate jpanel(s) code.
Comments
Post a Comment