JFrame Class

Package: javax.swing

The top-level component of most Swing-based applications is a “frame” and is defined by the JFrame class. By itself, a frame doesn’t do much, but to do anything else in Swing, you must first create a frame. Figure 5-6 shows a frame that does nothing but display the message Hello, World! in its title bar.

9781118239742-fg0506.tif

Figure 5-6

Constructors

Constructor

Description

JFrame()

Creates a new frame with no title

JFrame(String title)

Creates a new frame with the specified title

Methods

Method

Description

void add(Component c)

Adds the specified component to the frame.

JMenuBar getJMenuBar()

Gets the menu for this frame.

void pack()

Adjusts the size of the frame to fit the components you added to it.

void remove(Component c)

Removes the specified component from the frame.

void setDefaultClose Operation

Sets the action taken when the user closes the frame. You should almost always specify JFrame.EXIT_ON_CLOSE.

void setIconImage(Icon image)

Sets the icon displayed when the frame is minimized.

void setLayout(Layout Manager layout)

Sets the layout manager used to control how components are arranged when the frame is displayed. The default is the BorderLayout manager.

void setLocation(int x, int y)

Sets the x and y positions of the frame onscreen. The top-left corner of the screen is 0, 0.

void setLocation RelativeTo(Component c)

Centers the frame onscreen if the parameter is null.

void setResizeable(boolean value)

Sets whether the size of the frame can be changed by the user. The default setting is true (the frame can be resized).

void setSize(int width, int height)

Sets the size of the frame to the specified width and height.

void setJMenuBar(JMenuBar menu)

Sets the menu for this frame.

At minimum, you want to set a title for a new frame, set the frame’s size large enough for the user to see any components you add to it (by default, the frame is 0 pixels wide and 0 pixels high, so it isn’t very useful), and call the setVisible method to make the frame visible. Here’s one way to do that:

JFrame frame = new JFrame(“This is the title”);

frame.setSize(350, 260);

frame.setVisible(true);

It’s more common to create a class that extends the JFrame class. Then you can call these methods in the constructor. For example:

import javax.swing.*;

public class HelloFrame extends JFrame

{

public static void main(String[] args)

{

new HelloFrame();

}

public HelloFrame()

{

this.setSize(200,100);

this.setDefaultCloseOperation(

JFrame.EXIT_ON_CLOSE);

this.setTitle(“Hello World!”);

this.setVisible(true);

}

}

The preceding program is what I used to create the frame shown in Figure 5-6.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset