JAVA BASIC WINDOW
First I will show you how the base code for a java gui application is created. We will be creating a simple window with a button that will print text to the console.
Install Eclipse
- Should already be installed, if not, download / install the latest from eclipse.org
Create a new Java Project
- Locate FILE -> NEW -> Java Project
- Name the project whatever you want, I simply named mine "JavaWindowTesting"
- Click Finish
Create a package
Unlike in Android studio, we need to create the file structure for java to run correctly. We need to create a new package to store our .java classes.
- On the navigation view, open your project
- Right click on the "src" (source) folder
- Locate NEW -> PACKAGE
- Name the package whatever you want, I named it "testing"
Create a class
- Right click on your package and locate NEW -> Class
- Name it whatever. I named it "WindowTesting"
Create the main method
The java main method can be a bit confusing at times. Just memorize it and its much easier to deal with.
Add the code as follows:
public static void main(String[] args){ }
The main method is used to start a java application. The computer will look for this method to start execution.
Create a JFrame (Java Window)
In order to create a window in java, we need to use the built-in java API: Swing (More commonly known as JFrame)
Create a static Jframe (above the main method, not inside)
public static JFrame frame;
- Instantiate the frame under the main method. (Do not make another main, use the one we just made)
As an argument for Jframe, give it a String that will be the title of your window.
public static void main(String[] args) { frame = new JFrame("A new window! :D"); }
Set the bounds of the window (set the size it will appear on the screen)
frame.setSize(640, 480);
Set the frame to be visible.
frame.setVisible(true);
- (Optional) Set frame layout to null. This fixes the issue of objects filling your screen instead of correctly positioning themselves.
frame.setLayout(null);
Test your window. Press the green play button and choose Java Application.