120 likes | 242 Views
This guide covers advanced Java Swing techniques for interactive graphics manipulation. It explains how to handle mouse events effectively—tracking clicks, drags, and movements—to allow dynamic interaction with custom components. You'll learn about hit testing, managing GUI components like JButtons, and rendering graphics efficiently while preserving the background. Topics include using double buffering to reduce flashing, optimizing repainting for better performance, and leveraging custom graphics for intuitive user experiences. Perfect for developers looking to enhance their HCI projects with Java.
E N D
Java Direct Manipulation Chris North cs3724: HCI
Java Review • Java • Swing components, Layout managers • Events • Graphics • JDBC, MVC
Hit Testing • Mouse click, mouse over • Which dot did user click on? • Using components: • Make each dot a simple component, like a JButton • Hit testing automatic, each component is a subwindow • Listen to each component • Receive event, check event source • rectangular items, scalability, customize JComponent • Using custom graphics: • Get click event x,y from JPanel • Iterate through data structure, test for hit • Or, shape.contains(x,y) • Data structure for fast lookup?
Manipulation • Dragging, stretching, … • MouseDrag, MouseMove events • Using components: • mousePressed store x,y click in component • mouseDragged • Calculate delta • Move component by delta • Using graphics: • (need to erase it, repaint other graphics, repaint new item) • Calculate delta, calculate new item location, store • Call repaint( ) • Draw new graphics in paintComponent( )
Problem • Dynamic manipulation on top of other graphics • Need to preserve (redraw) other graphics • Examples: MacDraw, powerpoint • Simple solution: • Call repaint( ) while dragging • paintComponent( ) restores other graphics • But: lots of graphics, too slow!
Solutions • Minimize repaint rectangle: • mypanel.repaint(rect) where rect is area of manipulation • paintComponent( ) process only graphics in rect • Modified double buffering: • maintain buffer for background graphics • Paint buffer to screen, then paint manip graphics • XOR painting: • Draw manipulations by inverting pixel colors • drawing with XOR twice returns to original look • graphics.setXORMode(color) • graphics.setPaintMode( ) for normal painting
Drag-n-Drop • Drag and Drop API • Data transfer
Problem: Flashing • Ugly flashing when repaint: • Paint background • Redraw shapes
Solution: Double buffering • Double buffered repaint: • Draw all graphics in temporary off-screen image • Paint background color • Paint shapes • Then paint image to JPanel • Bonus: Swing does this for you! • Draw graphics on JPanel • JPanel maintains off-screen image