How To Create A Window In Java
A Frame is a top-level window with a championship and a edge. The size of the frame includes whatsoever area designated for the border. The dimensions of the border area may be obtained using the getInsets
method. Since the border expanse is included in the overall size of the frame, the border effectively obscures a portion of the frame, constraining the expanse bachelor for rendering and/or displaying subcomponents to the rectangle which has an upper-left corner location of (insets.left
, insets.elevation)
, and has a size of width - (insets.left + insets.correct)
past summit - (insets.top + insets.lesser)
.
A frame, implemented every bit an instance of the JFrame
grade, is a window that has decorations such as a edge, a championship, and supports button components that shut or iconify the window. Applications with a GUI usually include at to the lowest degree 1 frame. Applets sometimes use frames, every bit well.
To make a window that is dependent on some other window — disappearing when the other window is iconified, for example — use a dialog
instead of frame.
. To brand a window that appears within another window, use an internal frame.
Creating and Showing Frames
Hither is a motion-picture show of the extremely plain window created past the FrameDemo
sit-in awarding. Y'all tin can find the source lawmaking in FrameDemo.coffee
. You can run FrameDemo ( download JDK 7 or subsequently).
The post-obit FrameDemo
code shows how to create and ready a frame.
//i. Create the frame. JFrame frame = new JFrame("FrameDemo"); //2. Optional: What happens when the frame closes? frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //3. Create components and put them in the frame. //...create emptyLabel... frame.getContentPane().add together(emptyLabel, BorderLayout.Middle); //4. Size the frame. frame.pack(); //5. Show information technology. frame.setVisible(truthful);
Here are some details about the code:
- The first line of lawmaking creates a frame using a constructor that lets yous set the frame title. The other frequently used
JFrame
constructor is the no-argument constructor. - Next the code specifies what happens when your user closes the frame. The
EXIT_ON_CLOSE
operation exits the plan when your user closes the frame. This behavior is advisable for this program because the program has only 1 frame, and closing the frame makes the programme useless.See Responding to Window-Closing Events for more than information.
- The next bit of code adds a bare label to the frame content pane. If you're not already familiar with content panes and how to add components to them, please read Adding Components to the Content Pane.
For frames that have menus, you'd typically add the card bar to the frame here using the
setJMenuBar
method. Run across How to Use Menus for details. - The
pack
method sizes the frame then that all its contents are at or in a higher place their preferred sizes. An alternative topack
is to establish a frame size explicitly by callingsetSize
orsetBounds
(which also sets the frame location). In full general, usingpack
is preferable to callingsetSize
, sincepack
leaves the frame layout manager in charge of the frame size, and layout managers are good at adjusting to platform dependencies and other factors that affect component size.This example does not set the frame location, simply information technology is easy to exercise and then using either the
setLocationRelativeTo
orsetLocation
method. For case, the following code centers a frame onscreen:frame.setLocationRelativeTo(nix);
- Calling
setVisible(true)
makes the frame appear onscreen. Sometimes you might see theshow
method used instead. The two usages are equivalent, just we usesetVisible(true)
for consistency'southward sake.
Specifying Window Decorations
By default, window decorations are supplied by the native window system. Notwithstanding, y'all can request that the await-and-experience provide the decorations for a frame. You lot can also specify that the frame take no window decorations at all, a characteristic that can be used on its own, or to provide your ain decorations, or with full-screen exclusive mode.
Besides specifying who provides the window decorations, you can also specify which icon is used to represent the window. Exactly how this icon is used depends on the window organization or wait and feel that provides the window decorations. If the window organization supports minimization, then the icon is used to represent the minimized window. Most window systems or look and feels likewise display the icon in the window decorations. A typical icon size is 16x16 pixels, only some window systems use other sizes.
The post-obit snapshots evidence three frames that are identical except for their window decorations. Equally you can tell past the advent of the push button in each frame, all three use the Java await and feel. The start uses decorations provided by the window system, which happen to be Microsoft Windows, just could as easily be any other system running the Java platform.The second and third use window decorations provided by the Java wait and feel. The third frame uses Java expect and feel window decorations, only has a custom icon.
Here is an case of creating a frame with a custom icon and with window decorations provided by the await and feel:
//Ask for window decorations provided by the look and feel. JFrame.setDefaultLookAndFeelDecorated(true); //Create the frame. JFrame frame = new JFrame("A window"); //Set the frame icon to an prototype loaded from a file. frame.setIconImage(new ImageIcon(imgURL).getImage());
As the preceding lawmaking snippet implies, yous must invoke the setDefaultLookAndFeelDecorated
method earlier creating the frame whose decorations you wish to bear upon. The value yous prepare with setDefaultLookAndFeelDecorated
is used for all subsequently created JFrame
southward. You can switch back to using window system decorations by invoking JFrame.setDefaultLookAndFeelDecorated(faux)
. Some look and feels might not back up window decorations; in this example, the window organization decorations are used.
The full source code for the application that creates the frames pictured above is in FrameDemo2.java
. As well showing how to cull window decorations, FrameDemo2 also shows how to disable all window decorations and gives an example of positioning windows. It includes two methods that create the Paradigm
objects used as icons — one is loaded from a file, and the other is painted from scratch.
Try this::
- Click the Launch button to run the Frame Demo using Coffee™ Spider web First (download JDK vii or later). Alternatively, to compile and run the example yourself, consult the example index.
- Bring up two windows, both with look-and-feel-provided decorations, but with different icons.
The Java look and feel displays the icons in its window decorations. Depending on your window system, the icon may be used elsewhere to represent the window, specially when the window is minimized. - Bring upward i or more than windows with window system decorations.
Run into if your window system treats these icons differently. - Bring upward ane or more windows with no window decorations.
Play with the various types of windows to see how the window decorations, window system, and frame icons interact.
Responding to Window-Closing Events
By default, when the user closes a frame onscreen, the frame is hidden. Although invisible, the frame still exists and the program tin arrive visible again. If you want different behavior, and so you demand to either register a window listener that handles window-endmost events, or you need to specify default close behavior using the setDefaultCloseOperation
method. You can fifty-fifty practice both.
The argument to setDefaultCloseOperation
must be i of the post-obit values, the first three of which are divers in the WindowConstants
interface (implemented by JFrame
, JInternalPane
, and JDialog
):
-
DO_NOTHING_ON_CLOSE
- Do non do anything when the user requests that the window close. Instead, the program should probably use a window listener that performs some other activity in its
windowClosing
method. -
HIDE_ON_CLOSE
(the default forJDialog
andJFrame
) - Hide the window when the user closes it. This removes the window from the screen but leaves information technology displayable.
-
DISPOSE_ON_CLOSE
(the default forJInternalFrame
) - Hide and dispose of the window when the user closes it. This removes the window from the screen and frees up any resource used by information technology.
-
EXIT_ON_CLOSE
(defined in theJFrame
class) - Exit the awarding, using
System.exit(0)
. This is recommended for applications only. If used within an applet, aSecurityException
may be thrown.
Note:
DISPOSE_ON_CLOSE
can have results similar to EXIT_ON_CLOSE
if merely one window is onscreen. More precisely, when the last displayable window within the Java virtual machine (VM) is tending of, the VM may terminate. See AWT Threading Issues for details.
The default close operation is executed afterwards any window listeners handle the window-endmost event. So, for example, presume that you specify that the default close operation is to dispose of a frame. You too implement a window listener that tests whether the frame is the last one visible and, if so, saves some data and exits the application. Under these conditions, when the user closes a frame, the window listener volition be called first. If information technology does non exit the application, then the default shut operation — disposing of the frame — will then exist performed.
For more data virtually treatment window-closing events, encounter How to Write Window Listeners. Besides handling window-closing events, window listeners tin can also react to other window land changes, such as iconification and activation.
The Frame API
The following tables list the ordinarily used JFrame
constructors and methods. Other methods y'all might want to call are defined by the java.awt.Frame
, coffee.awt.Window
, and java.awt.Component
classes, from which JFrame
descends.
Considering each JFrame
object has a root pane, frames accept support for interposing input and painting behavior in front of the frame children, placing children on unlike "layers", and for Swing menu confined. These topics are introduced in Using Superlative-Level Containers and explained in particular in How to Apply Root Panes.
The API for using frames falls into these categories:
- Creating and Setting Up a Frame
- Setting the Window Size and Location
- Methods Related to the Root Pane
Method or Constructor | Purpose |
---|---|
JFrame() JFrame(String) | Create a frame that is initially invisible. The String argument provides a title for the frame. To brand the frame visible, invoke setVisible(truthful) on information technology. |
void setDefaultCloseOperation(int) int getDefaultCloseOperation() | Set or get the performance that occurs when the user pushes the close push on this frame. Possible choices are:
WindowConstants interface, which JFrame implements. The EXIT_ON_CLOSE constant is divers in the JFrame class. |
void setIconImage(Image) Paradigm getIconImage() (in Frame ) | Fix or get the icon that represents the frame. Note that the argument is a coffee.awt.Prototype object, not a javax.swing.ImageIcon (or any other javax.swing.Icon implementation). |
void setTitle(String) Cord getTitle() (in Frame ) | Set or get the frame championship. |
void setUndecorated(boolean) boolean isUndecorated() (in Frame ) | Gear up or get whether this frame should be decorated. Works simply if the frame is not withal displayable (has not been packed or shown). Typically used with total-screen exclusive style or to enable custom window decorations. |
static void setDefaultLookAndFeelDecorated(boolean) static boolean isDefaultLookAndFeelDecorated() | Determine whether later on created JFrame s should have their Window decorations (such equally borders, and widgets for closing the window) provided by the current expect-and-feel. Note that this is only a hint, every bit some await and feels may not support this feature. |
Method | Purpose |
---|---|
void pack() (in Window ) | Size the window so that all its contents are at or above their preferred sizes. |
void setSize(int, int) void setSize(Dimension) Dimension getSize() (in Component ) | Set or go the full size of the window. The integer arguments to setSize specify the width and acme, respectively. |
void setBounds(int, int, int, int) void setBounds(Rectangle) Rectangle getBounds() (in Component ) | Set or get the size and position of the window. For the integer version of setBounds , the window upper left corner is at the ten, y location specified by the get-go ii arguments, and has the width and height specified by the terminal 2 arguments. |
void setLocation(int, int) Point getLocation() (in Component ) | Set or get the location of the upper left corner of the window. The parameters are the x and y values, respectively. |
void setLocationRelativeTo(Component) (in Window ) | Position the window so that it is centered over the specified component. If the argument is null , the window is centered onscreen. To properly center the window, you should invoke this method later the window size has been set. |
Method | Purpose |
---|---|
void setContentPane(Container) Container getContentPane() | Set or get the frame content pane. The content pane contains the visible GUI components within the frame. |
JRootPane createRootPane() void setRootPane(JRootPane) JRootPane getRootPane() | Create, set, or get the frame root pane. The root pane manages the interior of the frame including the content pane, the glass pane, and and so on. |
void setJMenuBar(JMenuBar) JMenuBar getJMenuBar() | Set or get the frame menu bar to manage a set of menus for the frame. |
void setGlassPane(Component) Component getGlassPane() | Set or get the frame drinking glass pane. You can use the glass pane to intercept mouse events or paint on summit of your program GUI. |
void setLayeredPane(JLayeredPane) JLayeredPane getLayeredPane() | Set or get the frame layered pane. You can employ the frame layered pane to put components on top of or behind other components. |
Examples that Use Frames
All of the standalone applications in this trail utilise JFrame
. The post-obit tabular array lists a few and tells you where each is discussed.
Example | Where Described | Notes |
---|---|---|
FrameDemo | The Case Explained | Displays a basic frame with 1 component. |
FrameDemo2 | Specifying Window Decorations | Lets you create frames with various window decorations. |
Framework | — | A study in creating and destroying windows, in implementing a carte du jour bar, and in exiting an application. |
LayeredPaneDemo | How to Use Layered Panes | Illustrates how to apply a layered pane (but non the frame layered pane). |
GlassPaneDemo | The Glass Pane | Illustrates the use of a frame drinking glass pane. |
MenuDemo | How to Use Menus | Shows how to put a JMenuBar in a JFrame . |
How To Create A Window In Java,
Source: https://docs.oracle.com/javase/tutorial/uiswing/components/frame.html
Posted by: stetlerportalime.blogspot.com
0 Response to "How To Create A Window In Java"
Post a Comment