Hello World (Java, Swing)

From LiteratePrograms

Jump to: navigation, search
Other implementations: Ada | ALGOL 68 | Alice ML | Amiga E | Applescript | AspectJ | Assembly Intel x86 Linux | Assembly Intel x86 NetBSD | AWK | bash | BASIC | Batch files | C | C, Cairo | C, Xlib | Candle | Clojure | C++ | C# | Delphi | Dylan | E | Eiffel | Erlang | Forth | FORTRAN | Fortress | Go | Groovy | Haskell | Hume | IBM PC bootstrap | Inform 7 | Java | Java, Swing | JavaScript | LaTeX | Lisp | Logo | Lua | Maple | MATLAB | Mercury | OCaml/F Sharp | occam | Oz | Pascal | Perl | PHP | Pic | PIR | PLI | PostScript | Prolog | Python | Rexx | Ruby | Scala | Scheme | Seed7 | sh | Smalltalk | SQL | Standard ML | SVG | Tcl | Tcl Tk | Visual Basic | Visual Basic .NET | XSL

This article explains how to print "Hello, World!" using Swing, a GUI toolkit for Java.

Source code

We declare that we are going to use a couple of particular packages.

<<SwingHelloWorld.java>>=
import java.awt.*;
import javax.swing.*;

The SwingHelloWorld class is a subclass of JFrame class. When we create a SwingHelloWorld instance, a window containing a "Hello, World!" string will pop up. The argument "Swing Example" is the title of the window.

<<SwingHelloWorld.java>>=
public class SwingHelloWorld extends JFrame {
  constructor	
  public static void main(String argv[]) {
    new SwingHelloWorld("Swing Example");
  }
}

The constructor contains every information we need to create a GUI. It begins with calling the superclass' constructor to set the title of the window.

<<constructor>>=
  public SwingHelloWorld(String name) {
    super(name);

Then we tell when to close the application.

<<constructor>>=
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);

The JLabel instance displays the string provided to the JLabel constructor. We set the appropriate size to JLabel instance and append it to the panel.

<<constructor>>=
    JLabel label = new JLabel("Hello, world!");
    label.setPreferredSize(new Dimension(210, 80));
    this.getContentPane().add(label);

The constructor ends with displaying the window.

<<constructor>>=
    this.pack();
    this.setVisible(true);
  }

External links

  • Example One: Your First Swing Program from the official java web site.
Download code
Views
Personal tools