Java GUI

Desktop GUI applications

Swing v.s. AWT

AWT Packages

Container

Top Lever Containers

Secondary Containers

Frame

By default, frame’s size is (0,0) and visibility is false;

f = new Frame();
f.setSize(500, 500);
f.setVisible(true);

Event Handing

Work Flow

java_awt_flow

notice: Listener interfaces are abstract, must override all methods; to avoid using interface, we can use(extends) the adapter (class)

Example

code source from https://www3.ntu.edu.sg/home/ehchua/programming/java/J4a_GUI.html

import java.awt.*;       // Using AWT layouts
import java.awt.event.*; // Using AWT event classes and listener interfaces
import javax.swing.*;    // Using Swing components and containers

// A Swing GUI application inherits from top-level container javax.swing.JFrame
public class SwingCounter extends JFrame {   // JFrame instead of Frame
   private JTextField tfCount;  // Use Swing's JTextField instead of AWT's TextField
   private JButton btnCount;    // Using Swing's JButton instead of AWT's Button
   private int count = 0;
 
   // Constructor to setup the GUI components and event handlers
   public SwingCounter () {
      // Retrieve the content-pane of the top-level container JFrame
      // All operations done on the content-pane
      Container cp = getContentPane();
      cp.setLayout(new FlowLayout());
 
      cp.add(new JLabel("Counter"));
      tfCount = new JTextField("0", 10);
      tfCount.setEditable(false);
      cp.add(tfCount);
 
      btnCount = new JButton("Count");
      cp.add(btnCount);
 
      btnCount.addActionListener(new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent evt) {
            ++count;
            tfCount.setText(count + "");
         }
      });
 
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setTitle("Swing Counter");
      setSize(300, 100);
      setVisible(true);
   }
 
   public static void main(String[] args) {
      // Run the GUI construction in the Event-Dispatching thread for thread-safety
      SwingUtilities.invokeLater(new Runnable() {
         @Override
         public void run() {
            new SwingCounter(); // Let the constructor do the job
         }
      });
   }
}
Fork me on GitHub