Displaying Graphics with Graphics2D |
To allow the user to interact with the graphics that you display, you need to be able to determine when the user clicks on one of them. TheGraphics2D
hit
method provides a way for you to easily determine if a mouse click occurred over a particularShape
. Alternatively, you can get the location of the mouse click and callcontains
on theShape
to determine if the click was within the bounds of theShape
.If you are using primitive text, you can perform simple hit testing by getting the outline
Shape
that corresponds to the text and callinghit
orcontains
with thatShape
. Supporting text editing requires much more sophisticated hit testing. If you want to allow the user to edit text, you should generally use one of the Swing editable text components. If you are working with primitive text and are usingTextLayout
to manage the shaping and positioning of the text, you can also useTextLayout
to perform hit testing for text editing. For more information, see the Text and Fonts chapter in the Java 2D Programmer's Guide.Example: ShapeMover
TheShapeMover
applet allows the user to drag aShape
around within the applet window. TheShape
is redrawn at every mouse location to provide feedback as the user drags it. Thecontains
method is called to determine whether or not the cursor is within the bounds of the rectangle when the mouse is pressed. If it is, the location of the rectangle is updated:public void mousePressed(MouseEvent e){ last_x = rect.x - e.getX(); last_y = rect.y - e.getY(); if(rect.contains(e.getX(), e.getY())) updateLocation(e); ... public void updateLocation(MouseEvent e){ rect.setLocation(last_x + e.getX(), last_y + e.getY()); repaint();ShapeMover.java
contains the complete code for this program.ShapeMover.html
includes the applet.You might notice that redrawing the
Shape
at every mouse location is slow--this is because the filled rectangle is re-rendered every time it is moved. Using double-buffering can eliminate this problem. If you use Swing, the drawing will be double buffered automatically--you don't have to change the rendering code at all. The code for a Swing version of this program is inSwingShapeMover.java
and an HTML file that includes the applet is here:SwingShapeMover.html
.If you're not using Swing, Example: BufferedShapeMover shows how you can implement double-buffering using a
BufferedImage--
you render into theBufferedImage
and then copy the image to the screen.
Displaying Graphics with Graphics2D |