First Swing Component

In your source code, you include the Swing package by adding an import statement:

import javax.swing.*;
Now you’re ready to replace your Button objects with JButton objects. We’ll also set up the application to take advantage of Swing’s L&F capabilities; we’ve put another row of buttons at the bottom of the frame that let you select one of the standard L&Fs:

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

public class ToolbarFrame2 extends Frame {

  // This time, let's use JButtons!
  JButton cutButton, copyButton;

  public ToolbarFrame2( ) {
    super("Toolbar Example (Swing)");
    setSize(250, 250);

    addWindowListener(new WindowAdapter( ) {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });

    ActionListener printListener = new ActionListener( ) {
      public void actionPerformed(ActionEvent ae) {
        System.out.println(ae.getActionCommand( ));
      }
    };
  
    // JPanel works similarly to Panel, so we'll use it.
    JPanel toolbar = new JPanel( );
    toolbar.setLayout(new FlowLayout(FlowLayout.LEFT));

    cutButton = new JButton("Cut");
    cutButton.addActionListener(printListener);
    toolbar.add(cutButton);

    copyButton = new JButton("Copy");
    copyButton.addActionListener(printListener);
    toolbar.add(copyButton);

    add(toolbar, BorderLayout.NORTH);
  }

  public static void main(String args[]) {
    ToolbarFrame2 tf2 = new ToolbarFrame2( );
    tf2.setVisible(true);
  }
}