Frame window program in java

Frame window program in java

Note: The specific decorations on a frame are system-dependent. You cannot change the decorations on a frame.

Below is the code from FrameDemo.java that creates the frame in the previous example.

public static void main(String s[]) < JFrame frame = new JFrame("A Basic Frame"); WindowListener l = new WindowAdapter() < public void windowClosing(WindowEvent e) < System.exit(0); >>; frame.addWindowListener(l); JLabel aLabel = new JLabel("Something to look at", new ImageIcon("images/beach.gif"), JLabel.CENTER); aLabel.setVerticalTextPosition(JLabel.TOP); aLabel.setHorizontalTextPosition(JLabel.CENTER); frame.getContentPane().add(aLabel, BorderLayout.CENTER); frame.pack(); frame.setVisible(true); >

The code creates a frame with the title A Basic Frame and adds a window listener to it that will exit the program when the user closes the frame.

The italic lines of code create the label that displays the text and image in the frame. This is essentially this program’s GUI. If you use this program as a framework for your own program, replace the italicized code to create the components that make up your program’s GUI.

The bold line adds the label to the frame’s content pane. Refer to Adding Components to a Frame for further details and examples.

For a frame to appear on the screen, a program must either call setSize or pack , and then call setVisible(true) or its equivalent, show . This program packs the frame and uses setVisible . Note that if any of the GUI is already visible, you should invoke setVisible from the event dispatching thread. Refer to the Threads and Swing page.

Читайте также:  What is custom php ini

This code is typical of many programs and is the framework we used to create many of the examples for this lesson (including GlassPaneDemo.java and BorderDemo.java ). Some examples in this lesson, such as TextFieldDemo.java and TableDemo.java , subclass JFrame and instantiate the frame subclass instead of JFrame . In these programs, the GUI is created in the constructor for the subclass. You might do this in your programs if you need to subclass JFrame for some reason.

  • To take advantage of new features provided by its root pane such as the glass pane and the layered pane.
  • JFrame lets you customize window closing behavior by calling the setDefaultCloseOperation method instead of writing a window listener.
  • JFrame supports the revalidate method. [PENDING: link to where revalidate is discussed]
  • Swing menus work best in a JFrame due to its setJMenuBar method.
  • You must use a JFrame in an applet if the applet uses Swing components. Also, we recommend that you use a JFrame in an application that uses Swing components, although it’s not required.

Adding Components to a Frame

    Create a container such as a JPanel , a JScrollPane , or a JTabbedPane , add components to it, then use JFrame.setContentPane to make it the frame’s content pane.

    TableDemo.java uses this technique. The code creates a scroll pane to use as the frame’s content pane. A table is in the scroll pane:

public class TableDemo extends JFrame < public TableDemo() < super("TableDemo"); MyTableModel myModel = new MyTableModel(); JTable table = new JTable(myModel); table.setPreferredScrollableViewportSize(new Dimension(500, 70)); //Create the scroll pane and add the table to it. JScrollPane scrollPane = new JScrollPane(table); //Add the scroll pane to this window. setContentPane(scrollPane); . . .
. //create the components. //get the content pane, add components to it: Container contentPane = getContentPane(); // use a layout manager that respects preferred sizes contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS)); contentPane.add(Box.createRigidArea(new Dimension(0, 10))); contentPane.add(controls); contentPane.add(Box.createRigidArea(new Dimension(0, 10))); contentPane.add(emptyArea);

The JFrame API

  • Creating and Setting Up a Frame
  • Setting or Getting the Frame’s Helper Objects
  • DO_NOTHING_ON_CLOSE
  • HIDE_ON_CLOSE (the default)
  • DISPOSE_ON_CLOSE

Источник

JFrame basic tutorial and examples

In the code above we create a frame window entitled “Demo program for JFrame”.

2. Setting layout manager

frame.setLayout(new GridBagLayout());
frame.setLayout(new GridLayout());
frame.setLayout(new CardLayout());
frame.setLayout(new FlowLayout());

NOTE: the call setLayout(layout) is equivalent to this call:

frame.getContentPane().setLayout(layout);

3. Adding child components to JFrame

  • We can use the method add(Component) to add a component to the frame’s content pane. For example, adding a text field:
JTextField textFieldUserName = new JTextField(50); frame.add(textFieldUserName);
frame.getContentPane().add(Component);
add(textFieldUserName, BorderLayout.CENTER);
GridBagConstraints constraint = new GridBagConstraints(); constraint.gridx = 1; constraint.gridy = 0; // set other constraints. JTextField textFieldUserName = new JTextField(20); add(textFieldUserName, constraint);

The method setJMenuBar(JMenuBar) is used to add a menu bar to the frame. The following example code adds a menu bar with a File > Exit menu:

JMenuBar menuBar = new JMenuBar(); JMenu menuFile = new JMenu("File"); JMenuItem menuItemExit = new JMenuItem("Exit"); menuFile.add(menuItemExit); menuBar.add(menuFile); // adds menu bar to the frame frame.setJMenuBar(menuBar);

4. Specifying window closing behavior for JFrame

We can specify which action will be executed when the user clicks on the frame’s close button:

frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

5. Showing JFrame on screen

frame.setSize(300, 200); frame.setVisible(true);

empty jframe window

Image:

It is recommended to instantiate and showing the frame in the Swing event dispatcher thread (EDT) like this:

SwingUtilities.invokeLater(new Runnable() < @Override public void run() < new SwingJFrameDemo().setVisible(true); >>);
frame.setLocationRelativeTo(null);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setLocation(new java.awt.Point(100, 100));
frame.setBounds(100, 100, 300, 400);
frame.setBounds(new java.awt.Rectangle(100, 100, 300, 400));

6. Handling window events for JFrame

The interface java.awt.event.WindowListener defines various window events to which we can listen if interested. The method addWindowListener(WindowListener) of JFrame class is used to add a window listener for the frame.

    Listen to window events by implementing the WindowListener interface: In this way, have the frame class implements the WindowListener interface and overrides all its methods, like the following example:

public class FrameDemo extends JFrame implements WindowListener < public FrameDemo() < super("Frame Demo"); // initialization code. setSize(300, 400); addWindowListener(this); setVisible(true); >public void windowActivated(WindowEvent event) < System.out.println("The window has been activated"); >public void windowClosed(WindowEvent event) < System.out.println("The window has been closed"); >public void windowClosing(WindowEvent event) < System.out.println("About to close the window"); >public void windowDeactivated(WindowEvent event) < System.out.println("The window has been deactivated"); >public void windowDeiconified(WindowEvent event) < System.out.println("The window has been restored"); >public void windowIconified(WindowEvent event) < System.out.println("The window has been minimized"); >public void windowOpened(WindowEvent event) < System.out.println("The window has been opened"); >>

In case we want to listen to only one (or more, but not all) events, we can create a listener class that extends from the WindowAdapter class and override only the interested event methods:

class MyWindowListener extends WindowAdapter < // overrides only one method: public void windowClosing(WindowEvent event) < System.out.println("About to close the window"); >>

Then add this listener for the frame as follows:

MyWindowListener listener = new MyWindowListener(); frame.addWindowListener(listener);

Or we can use anonymous class syntax like this:

addWindowListener(new WindowAdapter() < public void windowClosing(WindowEvent event) < System.out.println("About to close the window"); >>);

7. Customizing JFrame’s appearance

Image icon = new javax.swing.ImageIcon("images/android.png").getImage(); frame.setIconImage(icon);

Here the image android.png is placed under directory images which is relative to the application’s directory.
Image:

The icon image is in the classpath or in jar files:

String iconPath = "/net/codejava/swing/jframe/android.png"; Image icon = new ImageIcon(getClass().getResource(iconPath)).getImage(); frame.setIconImage(icon);
frame.getContentPane().setBackground(Color.GREEN);

If the frame is undecorated, its border, title bar and window buttons are all removed, only keep its content pane visible.

8. JFrame demo program

To demonstrate the techniques mentioned in this article and for your reference, we create a Swing program looks like the following:

jframe demo program

On clicking the close button, a confirm message dialog appears:

confirm message dialog

If “Yes” is selected, the program exits, otherwise the frame remains visible on screen.

You can download this demo program’s source code and executable jar file in the attachments section.

Other Java Swing Tutorials:

About the Author:

Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.

Источник

Class Frame

The size of the frame includes any area designated for the border. The dimensions of the border area may be obtained using the getInsets method, however, since these dimensions are platform-dependent, a valid insets value cannot be obtained until the frame is made displayable by either calling pack or show . Since the border area is included in the overall size of the frame, the border effectively obscures a portion of the frame, constraining the area available for rendering and/or displaying subcomponents to the rectangle which has an upper-left corner location of (insets.left, insets.top) , and has a size of width — (insets.left + insets.right) by height — (insets.top + insets.bottom) .

The default layout for a frame is BorderLayout .

A frame may have its native decorations (i.e. Frame and Titlebar ) turned off with setUndecorated . This can only be done while the frame is not displayable .

In a multi-screen environment, you can create a Frame on a different screen device by constructing the Frame with Frame(GraphicsConfiguration) or Frame(String title, GraphicsConfiguration) . The GraphicsConfiguration object is one of the GraphicsConfiguration objects of the target screen device.

In a virtual device multi-screen environment in which the desktop area could span multiple physical screen devices, the bounds of all configurations are relative to the virtual-coordinate system. The origin of the virtual-coordinate system is at the upper left-hand corner of the primary physical screen. Depending on the location of the primary screen in the virtual device, negative coordinates are possible, as shown in the following figure.

In such an environment, when calling setLocation , you must pass a virtual coordinate to this method. Similarly, calling getLocationOnScreen on a Frame returns virtual device coordinates. Call the getBounds method of a GraphicsConfiguration to find its origin in the virtual coordinate system.

The following code sets the location of the Frame at (10, 10) relative to the origin of the physical screen of the corresponding GraphicsConfiguration . If the bounds of the GraphicsConfiguration is not taken into account, the Frame location would be set at (10, 10) relative to the virtual-coordinate system and would appear on the primary physical screen, which might be different from the physical screen of the specified GraphicsConfiguration .

Frame f = new Frame(GraphicsConfiguration gc); Rectangle bounds = gc.getBounds(); f.setLocation(10 + bounds.x, 10 + bounds.y);
  • WINDOW_OPENED
  • WINDOW_CLOSING :
    If the program doesn’t explicitly hide or dispose the window while processing this event, the window close operation is canceled.
  • WINDOW_CLOSED
  • WINDOW_ICONIFIED
  • WINDOW_DEICONIFIED
  • WINDOW_ACTIVATED
  • WINDOW_DEACTIVATED
  • WINDOW_GAINED_FOCUS
  • WINDOW_LOST_FOCUS
  • WINDOW_STATE_CHANGED

Источник

Оцените статью