Создание меню
Листинг 13.2. Программа рисования с всплывающим меню.
import java.awt.*; import java.awt.event.*; public class PopupMenuScribble extends Frame{ public PopupMenuScribble(String s){ super (s); ScrollPane pane = new ScrollPane(); pane.setSize(300, 300); add(pane, BorderLayout.CENTER); Scribble scr = new Scribble(this, 500, 500); pane.add(scr); addWindowListener(new WinClose()); pack (); setVisible(true); } class WinClose extends WindowAdapter{ public void windowClosing(WindowEvent e){ System.exit(0); } } public static void main(String[] args){ new PopupMenuScribble(" \"Рисовалка\" с всплывающим меню"); } } class ScriBble extends Component implements ActionListener{ protected int lastX, lastY, w, h; protected Color currColor = Color.black; protected Frame f; protected PopupMenu c; public Scribble(Frame frame, int width, int height)!{ f = frame; w = width; h = height; enableEvents(AWTEvent.MOUSE_EVENT_MASK | AWTEvent.MOUSEJtoTIONJEVENT_MASK); с = new PopupMenu ("Цвет"); add(c); Menultera clear = new Menultem("Очистить", new MenuShortcut(KeyEvent.VK_D)); Menultem red = new Menultem("Красный"); Menultem green = new Menultem("Зеленый"); Menultem blue = new Menultern("Синий"); Menultem black = new Menultem("Черный"); c.add(red); c.add(green); c.add(blue); c.add(black); с.addSeparator(); с.add(clear); red.addActionListener(this); green.addActionListener(this); blue.addActionListener(this); black.addActionListener(this); clear.addActionListener(this); } public Dimension getPreferredSize() { return new Dimension(w, h); } public void actionPerformed(ActionEvent event){ String s = event.getActionCommand(); if (s.equals("Очистить")) repaint(); else if (s.equals("Красный")) currColor = Color.red; else if (s.equals("Зеленый")) currColor = Color.green; else if (s.equals("Синий")) currColor = Color.blue; else if (s.equals("Черный")) currColor = Color.black; } public void processMouseEvent(MouseEvent e){ if (e.isPopupTrigger()) c.show(e.getComponent (), e.getXO, e.getY()); else if (e.getlDO == MouseEvent.MOUSE_PRESSED){ lastX = e.getX(); lastY = e.getY(); } else super.processMouseEvent(e); } public void processMouseMotionEvent(MouseEvent e){ if (e.getlDO = MouseEvent.MOUSE_DRAGGED){ Graphics g = getGraphics(); g.setColor(currColor); g.drawLinedastX, lastY, e.getX(), e.getY()); lastX = e.getX(); lastY = e.getY(); } else super.processMouseMotionEvent(e); } }
Рис. 13.3. Программа рисования с всплывающим меню