/* * ===================================================================== * DemoScrollBar.java : .... * * Written by : John Vella; Appeared in Java Swing book .... * Converted to applet format by : Mark Austin March, 2001 * ===================================================================== */ import javax.swing.*; import javax.swing.event.MouseInputAdapter; import java.awt.*; import java.awt.event.*; import java.util.*; public class DemoScrollBar extends JApplet { int x, y; int flag; public void init() { // 1. Get the content pane and assign layout Container container = getContentPane(); // 2. Add the canvas with rectangles DemoScrollBarGraphics ct = new DemoScrollBarGraphics( this ); container.add( ct ); } } // 3. Implement the canvas with mouse listener ... class DemoScrollBarGraphics extends Canvas { DemoScrollBar dmm; public DemoScrollBarGraphics( DemoScrollBar dmm ) { this.dmm = dmm; this.dmm.setBackground(Color.white); this.dmm.addMouseListener(new DemoScrollBarMouseListener()); } // Paint the graphics .... public void paint(Graphics g) { // Fill canvas with background color .... g.setColor( Color.white ); g.fillRect(0, 0, getWidth(), getHeight()); // Write blue text on the canvas ...... g.setColor(Color.blue); g.drawString("Drag/Move the Mouse ...", 5, 20); g.setColor(Color.red); if( dmm.flag == 1 ) { g.drawString("Don't Move! Drag the Mouse!", 5, 85); g.drawString("Cursor Coordinates: " + dmm.x + ", " + dmm.y, 5, 95); } else if( dmm.flag == 2 ) { g.drawString("Don't Drag! Move the Mouse!", 5, 85); g.drawString("Cursor Coordinates: " + dmm.x + ", " + dmm.y, 5, 95); } } // 3. The update() method to repair the applet's background. // This can reduce the performance and lead to flickering. // The workaround is to use a JPanel attached to the applet. public void update(Graphics g) { g.setColor( this.getBackground() ); g.fillRect(0, 0, getWidth(), getHeight()); paint(g); } // Repaint the graphics .... void repaint(Graphics g) { g.setColor(Color.blue); g.drawString("You're in repaint() ...", 15, 20); } // Mouse listener for canvas .... class DemoScrollBarMouseListener extends MouseInputAdapter { // Executed when the mouse is clicked ... public void mouseClicked(MouseEvent me) { // Set the flag value // Get the coordinates of the mouse pointer. dmm.flag = 1; dmm.x = me.getX(); dmm.y = me.getY(); // Repaint the applet. dmm.repaint(); } // Executed when the mouse is released. public void mouseReleased(MouseEvent me) { // Set the flag value // Get the coordinates of the mouse pointer. dmm.flag = 2; dmm.x = me.getX(); dmm.y = me.getY(); // Repaint the applet. dmm.repaint(); } } }