Setting Up JFrame/Program Window

Introduction: Hello. This page will teach you how to use JFrames within Java. What is a JFrame? A JFrame is a Java component which is able to hold or contain multiple more components. The JFrame is the 'window' of the program (the outer part which has the re-size options, the minimize, maximize and close options as well as the title of the program and icon). Should I use a JFrame in my program? You should only use a JFrame if you need a GUI/UI in your program. If you are willing to use a CLI (Command Line Interface) through the console then a JFrame is not needed. Example: Here is an example of how to set up a JFrame for your program. First you need to have your public static main void method (which is the first method ran once the application is started). Within that method we want to either; create a new instance of a class (which I have done of a new class named "Frame"). Or, you can just run another method within the same class...
  1. public static void main(String args[]) {
  2. new Frame();
  3. }
Now that we have that we want to import two namespaces;
  1. import java.awt.Dimension;
  2. import javax.swing.JFrame;
The JFrame import is so we can simply use JFrames and the Dimension import is so we can set JFrame sizes. Next we want to make sure the class with the JFrame extends it, like so;
  1. public class Frame extends JFrame{}
Now for the JFrame itself, on the method ran (or if it is a new class, on the constructor) we want to create a new JFrame and give it some attributes. These are quite simple and should be easy to figure out. There are lots more options which you can check out, such as setResizable.
  1. JFrame frame = new JFrame();
  2. Dimension dim = new Dimension(1280, 720);
  3. frame.setMinimumSize(dim);
  4. frame.setMaximumSize(dim);
  5. frame.setPreferredSize(dim);
  6. frame.setTitle("This is our frame!");
  7. frame.setLocationRelativeTo(null);
  8. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  9. frame.setVisible(true);
  10. frame.pack();
Finished! There will be more tutorials on adding components to the JFrame in the near future (if they're not already uploaded).

Add new comment