Drawing Text


You can also draw text with the Graphics2D object's drawText method. When the user selects the Draw menu's Draw Text item, Painter displays a dialog box of the OkCancelDialog class (which you saw earlier in the Slapshot! game):

 class OkCancelDialog extends Dialog implements ActionListener {     Button ok, cancel;     TextField text;     public String data;     OkCancelDialog(Frame hostFrame, String title, boolean dModal)     {         super(hostFrame, title, dModal);         setSize(280, 100);         setLayout(new FlowLayout());         text = new TextField(30);         add(text);         ok = new Button("OK");         add(ok);         ok.addActionListener((ActionListener)this);         cancel = new Button("Cancel");         add(cancel);         cancel.addActionListener(this);         data = new String("");     }     public void actionPerformed(ActionEvent event)     {         if(event.getSource() == ok){             data = text.getText();         } else {             data = "";         }         setVisible(false);     } } 

This class displays a dialog box on request, and it stores the text the user has entered in its member named data. Here's how that text is stored in Painter's drawText variable:

 if(e.getSource() == textMenuItem){     textDialog.setVisible(true);     drawText = textDialog.data;     setFlagsFalse();     text = true;     textMenuItem.setState(true);     start.x = -20;     start.y = -20;     end.x = -20;     end.y = -20; } 

Now when the user clicks the mouse in the drawing area, that text will appear, with a shadow if required. Here's what that looks like in the paint method:

 if(text){     if(drawText != null && end != null && end.x !=0 &&         end.y !=0){         if(shadow){             paint = gImage.getPaint();             composite = gImage.getComposite();             gImage.setPaint(Color.black);             gImage.setComposite(AlphaComposite.getInstance                 (AlphaComposite.SRC_OVER, 0.3f));             gImage.drawString(drawText, end.x + 9, end.y + 9);             gImage.setPaint(paint);             gImage.setComposite(composite);         }         gImage.drawString(drawText, end.x, end.y);     } } 

You can see an example in Figure 4.7, where the user is entering text, complete with a drop shadow.

Figure 4.7. Drawing text, with a drop shadow.




    Java After Hours(c) 10 Projects You'll Never Do at Work
    Java After Hours: 10 Projects Youll Never Do at Work
    ISBN: 0672327473
    EAN: 2147483647
    Year: 2006
    Pages: 128

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net