Java Reference
In-Depth Information
JFrame aWindow = new JFrame("This is the Window Title");
int windowWidth = 400; // Window width in pixels
int windowHeight = 150; // Window height in pixels
aWindow.setBounds(50, 100, // Set position
windowWidth, windowHeight); // and size
aWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
aWindow.setVisible(true); // Display the window
The window is encapsulated by the JFrame object, aWindow . The setBounds() method for the aWindow
object determines the size and position of the application window. Calling setVisible() causes the win-
dow to be displayed. If you plug this code directly into the main() method, it surely displays the window,
but this is not the way to do it.
Preventing Deadlocks in GUI Code
Preparing the application window and any components it contains and displaying it is described as realizing
the window. Calling setVisible() for an application window object realizes the window. After the GUI for
an application has been realized, modifying or querying it on the main thread can cause deadlocks. Methods
for Swing components are not thread-safe so they must all execute in a separate thread from the main thread
to avoid the kinds of problems I described in Chapter 16. The thread in which you create the GUI and in
which all interactions with the GUI are dealt with is called the Swing event dispatching thread . Let's see
how you create an application window in an example.
TRY IT OUT: Creating an Application Window
Here's the code to create and display an application window:
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class TryWindow {
public static void createWindow(){
JFrame aWindow = new JFrame("This is the Window Title");
int windowWidth = 400;
// Window width
in pixels
int windowHeight = 150;
// Window height
in pixels
aWindow.setBounds(50, 100, // Set position
windowWidth, windowHeight); // and size
aWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
aWindow.setVisible(true);
// Display the
window
}
public static void main(String[] args) {
Search WWH ::




Custom Search