Toolbars2.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
Action objects and *two* toolbars!
*/
class Toolbars2 extends JFrame
{
// Just plop the main() method right in the frame class...
public static void main(String argv[])
{
Toolbars2 f = new Toolbars2();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.show();
}
public Toolbars2()
{
Toolkit kit = Toolkit.getDefaultToolkit();
Dimension ss = kit.getScreenSize();
setSize(ss.width/2,ss.height/3);
setLocation(ss.width/4,ss.height/4);
setTitle("CISC370-011 -- Actions with two toolbars");
JPanel sp = new JPanel();
Container contentPane = getContentPane();
contentPane.add(sp);
sp.setBackground(Color.BLACK);
// Create a File menu.
JMenuBar mbar = new JMenuBar();
setJMenuBar(mbar);
JMenu fileMenu = new JMenu("File");
mbar.add(fileMenu);
// Create a Color submenu.
JMenu optionsMenu = new JMenu("Colors");
fileMenu.addSeparator();
fileMenu.add(optionsMenu);
// Create a pair of toolbars.
JToolBar tb1 = new JToolBar("Color");
JToolBar tb2 = new JToolBar("Monochrome");
contentPane.add(tb1,BorderLayout.NORTH);
contentPane.add(tb2,BorderLayout.SOUTH);
// Define a list of colors and names.
class Bozo {
Color c;
String name;
Bozo(Color c,String name)
{ this.c = c; this.name = name; }
}
Bozo[] clist = {
new Bozo(Color.RED,"Red"),
new Bozo(Color.PINK,"Pink"),
new Bozo(Color.ORANGE,"Orange"),
new Bozo(Color.YELLOW,"Yellow"),
new Bozo(Color.GREEN,"Green"),
new Bozo(Color.CYAN,"Cyan"),
new Bozo(Color.BLUE,"Blue"),
new Bozo(Color.MAGENTA,"Magenta"),
new Bozo(Color.WHITE,"White"),
new Bozo(Color.LIGHT_GRAY,"Light gray"),
new Bozo(Color.GRAY,"Gray"),
new Bozo(Color.DARK_GRAY,"Dark gray"),
new Bozo(Color.BLACK,"Black"),
};
// Create an Action object for each color, and add it to
// buttons, menus, and one of the toolbars.
for (int i=0; i<clist.length; i++) {
ColorAction action =
new ColorAction(sp,clist[i].c,clist[i].name);
JButton button = new JButton(action);
sp.add(button);
JMenuItem option = new JMenuItem(action);
optionsMenu.add(option);
if (i % 2 == 0)
tb1.add(action);
else
tb2.add(action);
}
// Finally, add an Exit item to the File menu.
JMenuItem exitItem = new JMenuItem("Exit");
fileMenu.add(exitItem);
exitItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{ System.exit(0); }
});
}
}
/**
This class represents an <code>Action</code> that, whenever triggered,
sets the background of a given JPanel to a specified color.
*/
class ColorAction extends AbstractAction
{
public ColorAction(JPanel p,Color c,String name)
{
super(name);
this.color = c;
this.panel = p;
}
public void actionPerformed(ActionEvent e)
{
panel.setBackground(color);
}
private JPanel panel;
private Color color;
}