My first Java application

My first Java application

This tutorial shows how to create a Java application which shows "Hello World" in a Window. more >>

Contents

Create a file

Create a file named "C:\Java\HelloWorld.java". Open it
with a text editor.

HelloWorld Class

First we have to import javax.swing.*
which contains all neccessary stuff for
graphical user interfaces.

Then we have to create a class
which extends JFrame.

JFrame is a window with title and
close/maximize buttons.

Create the main method

The static method main(String[] args)
is a predefined method which is started
when you run your program.

Always use

public static void main(String[] args){
  [Your code]
}



Constructor

Create the Constructor.

public HelloWorld(){
     super("Hello World");
     getContentPane().add(new JLabel("Hello World"));
     pack();
}


The first line calls the constructor
of the parent class JFrame with the
window title "Hello World".

Then a label is added to the content frame
of the window.

Finally the window size is adapted
to its contents with pack();

Fill the main method

Now we have to fill the main method.

First we have to create an instance of
the HelloWorld class.
HelloWorld frame=new HelloWorld();


Then we have to make it visible with
frame.setVisible(true);

Start console

Start the console and change to
the bin folder of your JDK installation.

Compile the java file

Compile your Java file by entering

javac c:\Java\HelloWorld.java

Run your application

Change to c:\Java

and run your application

java HelloWorld