Setting Up JFrame/Program Window
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.
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...
Now that we have that we want to import two namespaces;
- import java.awt.Dimension;
- 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;
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.
- frame.setTitle("This is our frame!");
There will be more tutorials on adding components to the JFrame in the near future (if they're not already uploaded).