Java Swing

Image Credit: Wikipedia

Java Swing

  • Developed in late 1990s
  • Upgrade to
    Abstract Window Toolkit (AWT)
  • Object-Oriented, Inheritable
  • Change Look and Feel
  • Cross-Platform

Imports

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

Class Structure

public class MainWindow extends JFrame 
                        implements ActionListener {
public MainWindow() { // create GUI }
@Override public void actionPerformed(ActionEvent e) { // handle events }
public static void main(String[] args){ // start program } }

Layout

// sets the size of this window
this.setSize(new Dimension(200, 100));
// tell the program to exit when this window is closed this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// set the layout manager this.setLayout(new GridBagLayout());
// Create the constraints for the GridBagLayout manager GridBagConstraints gbc = new GridBagConstraints();

GridBagLayout

Image Credit: Oracle

GridBagLayout

Uses Rows & Columns

Image Credit: Oracle

GridBagLayout

Can Grow to Fit Screen

Image Credit: Oracle

Label

// set the constraints for the label
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 0;
// add a label this.add(new JLabel("Hello World!"), gbc);

Button

// reset the constraints for the button
gbc.gridx = 0;
gbc.gridy = 1;
// create a button JButton button = new JButton("Close"); // set the button's command: button.setActionCommand("close"); // send the clicked event to this object button.addActionListener(this); // add the button this.add(button, gbc);

Java Example

Handle Events

Specified by ActionListener interface

@Override
public void actionPerformed(ActionEvent e) {
    if ("close".equals(e.getActionCommand())) {
        // close button was clicked, so exit the application
        System.exit(0);
    }
}

Start Application

Use a Thread!

public static void main(String[] args){
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            new MainWindow().setVisible(true);
        }
    });
}