GUI Hello

Nicholas Duchon: Mar 31, 2017

Key Concepts:

  • Putting a String onto a JPanel
  • JFrame is local to the constructor
  • class extends JPanel
  • paint overrides method in JPanel
    • starts with call to super
  • minimal code for displaying JFrame
  • The AWT thread running the JFrame
    continues after the main thread is done.
  • Watch count change as the JFrame is resized.

This is a trivial hello world example using the GUI system in Java.




import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.BorderLayout;

public class HelloND extends JPanel {
  public static final long serialVersionUID = 123; // ND: junk
  int count = 0;

 
  public HelloND (String name) {
    setBackground (Color.cyan);

    JFrame jf = new JFrame ();
    jf.setLocationRelativeTo (null);
    jf.setTitle (name);
    jf.setSize (400, 200);
    jf.add (this, BorderLayout.CENTER);
    jf.setVisible (true);
    jf.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
  } // end constructor
 
  public void paint (Graphics g) {
    super.paint (g);
    g.drawString ("Hello, Nick " + count++, 10, 50);
  } // end method paintComponent
 
  public static void main (String args []) {
    new HelloND ("This is a test");
    System.out.println ("--- bye ---");
  } // end main
} // end class HelloND

End.