MainClass.java Source code

Java tutorial

Introduction

Here is the source code for MainClass.java

Source

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JToolBar;
import javax.swing.plaf.metal.MetalIconFactory;

public class MainClass {

    public static void main(String[] a) {
        final int STRING_POSITION = 1;
        Object buttonColors[][] = { { Color.RED, "RED" }, { Color.BLUE, "BLUE" }, { Color.GREEN, "GREEN" },
                { Color.BLACK, "BLACK" }, null, // separator
                { Color.CYAN, "CYAN" } };

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        ActionListener actionListener = new TheActionListener();

        JToolBar toolbar = new JToolBar();
        toolbar.setRollover(true);

        for (Object[] color : buttonColors) {
            if (color == null) {
                toolbar.addSeparator();
            } else {
                Icon icon = MetalIconFactory.getTreeComputerIcon();
                JButton button = new JButton(icon);
                button.setActionCommand((String) color[STRING_POSITION]);
                button.addActionListener(actionListener);
                toolbar.add(button);
            }
        }

        Action action = new ShowAction(toolbar);
        JButton button = new JButton(action);
        toolbar.add(button);

        Container contentPane = frame.getContentPane();
        contentPane.add(toolbar, BorderLayout.NORTH);
        JTextArea textArea = new JTextArea();
        JScrollPane pane = new JScrollPane(textArea);
        contentPane.add(pane, BorderLayout.CENTER);
        frame.setSize(350, 150);
        frame.setVisible(true);

    }

    public static class TheActionListener implements ActionListener {
        public void actionPerformed(ActionEvent actionEvent) {
            System.out.println(actionEvent.getActionCommand());
        }
    };

}

class ShowAction extends AbstractAction {
    Component parentComponent;

    public ShowAction(Component parentComponent) {
        super("About");
        putValue(Action.MNEMONIC_KEY, new Integer(KeyEvent.VK_A));
        putValue(Action.SMALL_ICON, MetalIconFactory.getFileChooserHomeFolderIcon());

        this.parentComponent = parentComponent;
    }

    public void actionPerformed(ActionEvent actionEvent) {
        JOptionPane.showMessageDialog(parentComponent, "About Swing", "About Box V2.0",
                JOptionPane.INFORMATION_MESSAGE);
    }
}