Beispiel: "Hallo Welt"

// HalloWelt.java MM 2004

/**
* Erzeugen eines Fensters mit Text und Button.
*/

import java.awt.*; // Color
import javax.swing.*; //JFrame, JPanel, JLabel
import java.awt.event.*; // Listener

public class HalloWelt
extends JFrame
implements ActionListener
{
// View
/**
* Content Pane, Darstellungsbereich des Fensters.
*/
private JPanel contentPane = new JPanel();

/**
* Label, fuer statischen Text.
*/
private JLabel lbHallo = new JLabel( "Hallo Welt!");

/**
* Schalter Setzen
*/
private JButton btSet = new JButton( "Set");

/**
* Schalter Abbruch
*/
private JButton btQuit = new JButton( "Quit");

/**
* Konstruktor.
*/
public HalloWelt()
{
this( "Hallo!", Color.white);
}

/**
* Konstruktor, baut das Fenster auf.
* @param titel Titelleistentext
* @param farbe Fensterhintergrundsfarbe
*/
public HalloWelt( String titel, Color farbe)
{
// Titelleiste
super( titel);

// Darstellungsbereich
contentPane.add( btSet);
contentPane.add( lbHallo);
contentPane.add( btQuit);
contentPane.setBackground( farbe);
setContentPane( contentPane);

// Listener
btSet.addActionListener( this);
btQuit.addActionListener( this);

// Fenster
pack();
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE);
setVisible( true);
}

/* ------------------------------------------------- */
// Controller
/**
* Ereignisverarbeitung
*/
public void actionPerformed( ActionEvent ae)
{
// Schalten
if( ae.getActionCommand().equals( "Set"))
{
float dummy1 = ( float)Math.random();
float dummy2 = ( float)Math.random();
float dummy3 = ( float)Math.random();
Color farbe = new Color( dummy1, dummy2, dummy3);

contentPane.setBackground( farbe);
}

// Abbruch
if( ae.getActionCommand().equals( "Quit"))
{
System.exit( 0);
}
}

/* ------------------------------------------------- */

/**
* Test.
*/
public static void main(String args[])
{
HalloWelt hallo =
new HalloWelt( "Hallo Welt GUI", Color.white);
}
}


Ergebnis:
Hallo Welt