Java Swing: Adding Components (Video Tutorial Part 2)

A tutorial on adding components to your Swing applicatio. This tutorial covers buttons, text areas and BorderLayout. I also show you some useful web pages, including the free WindowBuilderPro from Google and the Swing Visual Guide pages. In the next tutorial I'll show you how to use the highly flexible (if somewhat notorious) GridBagLayout.

After starting the video, click the maximise button to make it fullscreen so you can see the code!

Some useful links:

Window Builder Pro: in spite of the name, this is a FREE Eclipse plugin. The company, or at least its product, was purchased by Google in 2011 and released to the community. The plugin allows you to visually design Swing apps, although it's not always easy to use and doesn't fully insulate you from the underlying complexity in the same way that, say, the C# visual designer does. On the other hand it's a lot better than NetBeans and it allows you to switch between your own code and the visual designer, which is great.

Visual Guide to Swing Components (Oracle seems to have ditched this page, so I've linked to a copy someone's made): with code samples. You'll need this for sure!

Visual Guide to Swing Layouts: you'll need this too.

Screenshot of "finished" app:

Code For This Tutorial

Main app:

import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class App {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JFrame frame = new MainFrame("Hello World Swing!");
                frame.setSize(500, 400);

Window class:

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;

public class MainFrame extends JFrame {
    public MainFrame(String title) {
        // Set layout manager
        setLayout(new BorderLayout());
        // Create Swing component
        final JTextArea textArea = new JTextArea();
        JButton button = new JButton("Click me!");
        // Add Swing components to content pane
        Container c = getContentPane();
        c.add(textArea, BorderLayout.CENTER);
        c.add(button, BorderLayout.SOUTH);
        // Add behaviour
        button.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {