Explain the usage of JFrame with example
What is the function of JFrame in Java and how to declare JFrames? Can you give example of it? Thanks
What is the function of JFrame in Java and how to declare JFrames? Can you give example of it? Thanks
Â
The JFrame is the foremost window used to display the components that needs to be displayed on the screen. It is directly related to Swing which is the chief Java graphical user interface widget toolkit. It is a component of JFC or the Oracle’s Java Foundation Classes. Swing was designed to give a more complicated set of graphical user interface components than the previous AWT or Abstract Window Toolkit. The best way of explaining the use of JFrame is through example.
import javax.swing.*;
// Importing the package that contains all the Swing Components and Classes.
public class FrameExample {
   public static void main(String[] args) {
       //Schedule a job for the event-dispatching thread:
       //creating and showing this application's GUI.
       SwingUtilities.invokeLater(new Runnable() {
           public void run() {
               createAndShowGUI();
           }
       });
   }
   private static void createAndShowGUI() {
       //Create and set up the frame.
       //The string passed as an argument will be displayed
       //as the title.
       JFrame frame = new JFrame("[=] Hello World [=]");
       //Display the window.
       frame.setSize(400, 100);
       frame.setVisible(true);
   }Â
}
And here’s another one.
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
public class SwingExample implements Runnable {
   @Override
   public void run() {
       // Create the window
       JFrame f = new JFrame("Hello, World!");
       // Sets the behavior for when the window is closed
       f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       // Add a layout manager so that the button is not placed on top of the label
       f.setLayout(new FlowLayout());
       // Add a label and a button
       f.add(new JLabel("Hello, world!"));
       f.add(new JButton("Press me!"));
       // Arrange the components inside the window
       f.pack();
       // By default, the window is not visible. Make it visible.
       f.setVisible(true);
   }
   public static void main(String[] args) {
       SwingExample se = new SwingExample();
       // Schedules the application to be run at the correct time in the event queue.
       SwingUtilities.invokeLater(se);
   }
}