// Toolbar.java // The toolbar is a canvas that displays the // images (actually just text) of some "tools" // and responds to mouse presses on them. // These tools work like buttons from the users standpoint. // S. Tanimoto 1 Feb. 2000 import java.awt.*; import java.awt.event.*; import java.util.*; public class Toolbar extends Canvas { private Vector theTools; private static int width = 600, height = 100; private PolyDraw pd; private Controls ct; private FontMetrics fm; private int fontHeight; private int fontLeading; private TBTool currentTool; Toolbar(PolyDraw thePD) { pd = thePD; ct = pd.getControls(); addMouseListener(new MouseHandlerForToolbar()); setBackground(Color.yellow); setSize(width, height); theTools = new Vector(); int ystart = 50; theTools.addElement(new TBTool(050, ystart, 100, 30, "Poly", this)); theTools.addElement(new TBTool(200, ystart, 100, 30, "Edit", this)); theTools.addElement(new TBTool(350, ystart, 100, 30, "Delete", this)); } public String whichTool() { if (currentTool == null) return ""; return (currentTool.getName()); } class TBTool { int x, y, w, h; String name; Toolbar tb; boolean highlighted; TBTool(int theX, int theY, int theW, int theH, String theName, Toolbar theTB) { x = theX; y = theY; w = theW; h = theH; name = theName; tb = theTB; highlighted = false; } void paint(Graphics g) { if (highlighted) { g.setColor(Color.green); } else { g.setColor(Color.gray); } g.fillRect(x, y, w, h); g.setColor(Color.white); int nameWidth = fm.stringWidth(name); int xul = ((x + x + w) / 2) - (nameWidth / 2); int yul = y + (h/2) + ((fontHeight - fontLeading) / 2); g.drawString(name, xul, yul); } boolean hit(int hitX, int hitY) { return ( (hitX > x) && ((x + w) > hitX) &&(hitY > y) && ((y + h) > hitY) ); } void highlight() { // Highlights a particular tool (button) and // does some processing associated with it. highlighted = true; tb.repaint(); pd.getDrawCanvas().cancelSelecting(); if (name.equals("Poly")) { Polygon pg = new Polygon(); pg.setColor(ct.getColor()); pd.getDrawCanvas().addObject(pg); } if (name.equals("Delete")) { pd.getDrawCanvas().deleteSelected(); } } void unhighlight() { highlighted = false; tb.repaint(); } private String getName() { return name; } } public void paint(Graphics g) { g.setColor(Color.black); Font f = new Font("Helvetica", Font.BOLD, 20); g.setFont(f); fm = g.getFontMetrics(); fontHeight = fm.getHeight(); fontLeading = fm.getLeading(); for (Enumeration enum = theTools.elements(); enum.hasMoreElements();) { TBTool aTool = (TBTool) enum.nextElement(); aTool.paint(g); } } class MouseHandlerForToolbar extends MouseAdapter { public void mousePressed(MouseEvent e) { for (Enumeration enum = theTools.elements(); enum.hasMoreElements();) { TBTool aTool = (TBTool) enum.nextElement(); if (aTool.hit(e.getX(), e.getY())) { if (currentTool != null) currentTool.unhighlight(); currentTool = aTool; currentTool.highlight(); break; } } } } }