by Dinesh Thakur Category: Swing

Another way of creating an application window is by defining a new class that extends the JFrame class. The new class will inherit fields and methods from the JFrame class. This technique is a preferred style for creating GUI applications.

In this Example, we have created a class named JFrameClassExample that extends the JFrame class. The constructor of the JFrameClassExample class contains the statement that constructs the user interface.

The statements.

FlowLayout layout = new FlowLayout();

setLayout(layout);

sets the layout manager for the container object ( i.e. JFrame).

The statements used for creating and setting layout can be combined as follows,

setLayout(new FlowLayout);

The statement,

JFrameClassExample frame = new JFrameClassExample ();

in the main () method instantiates an object of JFrameClassExampleclass which invokes the default constructor. This constructor sets the layout of the frame to FlowLayout and adds two buttons using the add () method with labels OK and Cancel into it.

The statement,

frame.setTitle("JFrame Class in Java Example");

sets the specified argument as the title of the frame. The other statements in the main () method work as usual.

import javax.swing.*;

import java.awt.*;
class JFrameClassExample extends JFrame
{
    JFrameClassExample()
    {
         FlowLayout layout = new FlowLayout();
         setLayout(layout);
         JButton ok = new JButton("OK");
         JButton cancel = new JButton("Cancel");
         add(ok);
         add(cancel);
     }
}
 class JFrameClassJavaExample
 {
     public static void main(String args[])
    {
        JFrameClassExample frame = new JFrameClassExample();
        frame.setTitle("JFrame Class in Java Example");
        frame.setBounds(200,250,350,150);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

JFrame Class in Java Example





About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.



Related Articles