Java Reference
In-Depth Information
TRY IT OUT: Centering a Window
Here's the code:
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class TryWindow3 {
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.setSize(windowWidth, windowHeight);
// Set window
size
aWindow.setLocationRelativeTo(null);
// Center window
aWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
aWindow.setVisible(true);
// Display the
window
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createWindow();
}
});
}
}
TryWindow3.java
When you execute this, you should see the window displayed centered on your primary display.
How It Works
This example calls the setSize() method for aWindow to specify the dimension for the window. Calling
setLocationRelativeTo() with a null argument centers the window relative to the primary monitor.
Points and Rectangles
Before continuing with the Component class methods, let's digress briefly into more detail concerning the
Point and Rectangle classes, as they are going to come up quite often. As you've seen, both these classes
are defined in java.awt . You will find many of the methods provided by the Point and Rectangle classes
very useful when drawing in a window. Entities displayed in a window typically have Rectangle objects
Search WWH ::




Custom Search