Java Awt Components

From JavaProgramming

Overview of graphical components in JavaAwt. Simple examples of an application with a GraphicalUserInterface and a JavaApplet

Write a GUI application
  /* HelloWorldFrame.java */
  import java.awt.*;
  import java.awt.event.*;

public class HelloWorldFrame extends Frame { public static void main(String[] args) { HelloWorldFrame frame = new HelloWorldFrame(); Panel panel = new Panel(); frame.add(panel); // Add event listener to close the application frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); frame.setTitle("HelloWorldFrame?"); frame.setSize(400,320); // Call setVisible() to make the frame visible frame.setVisible(true); panel.getGraphics().drawString("Hello world!", 20, 20); } }

Write an Applet

  /* HelloWorldApplet.java */
  import java.awt.*;
  import java.applet.*;

public class HelloWorldApplet extends Applet { public void paint(Graphics g) { g.drawString("Hello world!", 20, 20); } }

Show an Applet on a website
  /* HelloWorldApplet.html */
  <html>
  <head>
  <title>
  Test HelloWorldApplet
  </title>
  </head>
  <body>
  <applet
    code     = "HelloWorldApplet.class"
    codebase = "."
    width    = "400"
    height   = "300"
  >
  </applet>
  </body>
  </html>

Write an Applet that can run as a GUI application

Graphical components may be included in both GUI applications and Applets. The program below demonstrates this.

  /* StandAloneApplet.java */
  import java.awt.*;
  import java.awt.event.*;
  import java.applet.*;

public class StandAloneApplet extends Applet { public void paint(Graphics g) { g.drawString("Hello world!", 20, 20); } public static void main(String[] args) { Frame frame = new Frame(); StandAloneApplet applet = new StandAloneApplet(); frame.add(applet); // Add event listener to close the application frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); frame.setTitle("Standalone Applet"); frame.setSize(400,320); frame.setVisible(true); } }


EditText of this page (last edited April 8, 2003) or FindPage with title or text search