// ToolBarV.java // Creating and using Vectors import java.awt.*; import java.applet.*; import java.awt.event.*; import java.util.*; // For Vector class public class ToolBarV extends Applet implements ActionListener { // Attributes String slogan = "Java, Java, Java!!!"; Vector toolBar = new Vector(); public void init() { // 1. Toolbar Panel Panel p = new Panel(); p.setLayout(new FlowLayout(FlowLayout.LEFT)); p.setBackground(Color.lightGray); // 2. Create the toolBar Buttons String[] captions = { "Red", "Blue", "Green", "Yellow", "Black" }; Button b; for (int i = 0; i < captions.length; i++) { b = new Button(captions[i]); b.addActionListener(this); p.add(b); toolBar.addElement(b); } // 3. Add the Panel to the top of the applet setLayout(new BorderLayout()); add(p, "North"); } public void actionPerformed(ActionEvent ae) { // 1. Retrieve source of click Object obj = ae.getSource(); // 2. Match it with toolBar Button int clicked = toolBar.indexOf(obj); // 3. Take action based upon Button pressed switch (clicked) { case 0: setBackground(Color.red); break; case 1: setBackground(Color.blue); break; case 2: setBackground(Color.green); break; case 3: setBackground(Color.yellow); break; case 4: setBackground(Color.black); break; } repaint(); } public void paint(Graphics g) { int height = getSize().height; int width = getSize().width; g.setFont(new Font("Serif", Font.BOLD + Font.ITALIC, 36)); FontMetrics fm = g.getFontMetrics(); int strWidth = fm.stringWidth(slogan); int x = width/2 - (strWidth/2); int y = height/2 + (fm.getHeight()/2); g.setColor(Color.white); g.drawString(slogan, x, y); } }