Swing (Java): Difference between revisions

Content deleted Content added
m External links: +{{Java desktop}}
Hello World: Edited example code for thread safety
Line 110:
 
public static void main(final String[] args) {
new HelloSwingUtilities.invokeLater(Hello::new);
}
}
Line 121:
The <code>'''Hello()'''</code> [[constructor (object-oriented programming)|constructor]] initializes the frame by first calling the superclass constructor, passing the parameter <code>"hello"</code>, which is used as the window's title. It then calls the '''{{Javadoc:SE|name=setDefaultCloseOperation(int)|javax/swing|JFrame|setDefaultCloseOperation(int)}}''' method inherited from <code>JFrame</code> to set the default operation when the close control on the title bar is selected to '''{{Javadoc:SE|javax/swing|WindowConstants|EXIT_ON_CLOSE}}'''{{snd}} this causes the <code>JFrame</code> to be disposed of when the frame is closed (as opposed to merely hidden), which allows the Java virtual machine to exit and the program to terminate. Next, a '''{{Javadoc:SE|javax/swing|JLabel}}''' is created for the string '''"Hello, world!"''' and the '''{{Javadoc:SE|name=add(Component)|java/awt|Container|add(java.awt.Component)}}''' method inherited from the {{Javadoc:SE|java/awt|Container}} superclass is called to add the label to the frame. The '''{{Javadoc:SE|name=pack()|java/awt|Window|pack()}}''' method inherited from the {{Javadoc:SE|java/awt|Window}} superclass is called to size the window and lay out its contents.
 
The <code>'''main()'''</code> method is called by the Java virtual machine when the program starts. It [[Object (computer science)|instantiates]] a new '''<code>Hello</code>''' frame and causes it to be displayed by calling the '''{{Javadoc:SE|name=setVisible(boolean)|java/awt|Component|setVisible(boolean)}}''' method inherited from the {{Javadoc:SE|java/awt|Component}} superclass with the boolean parameter <code>'''true'''</code>. The code uses the '''{{Javadoc:SE|name=invokeLater(Runnable)|javax/swing|SwingUtilities|invokeLater(java.lang.Runnable)}}''' method to invoke the constructor from the AWT [[event dispatching thread]] in order to ensure the code is executed in a [[thread-safe]] manner. Once the frame is displayed, exiting the <code>main</code> method does not cause the program to terminate because the AWT [[event dispatching thread]] remains active until all of the Swing top-level windows have been disposed.
 
===Window with Button===