import javax.swing.*; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.event.*; public class MouseMoveDemo extends JPanel implements AdjustmentListener, MouseMotionListener { JScrollBar jsx, jsy; JTextField text; int x = 50; int y = 50; int fx, fy; MyPanel pane; MouseMoveDemo() { jsx = new JScrollBar(JScrollBar.HORIZONTAL, x, 1, 0, 101); jsy = new JScrollBar(JScrollBar.VERTICAL, y, 1, 0, 101); jsx.addAdjustmentListener(this); jsy.addAdjustmentListener(this); // text = new JTextField(5); // this.add(text); pane = new MyPanel(); pane.addMouseMotionListener(this); this.setLayout(new BorderLayout()); this.add(pane, BorderLayout.CENTER); this.add(jsx, BorderLayout.SOUTH); this.add(jsy, BorderLayout.EAST); } public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } public static void createAndShowGUI() { JFrame frame = new JFrame("MouseMoveDemo"); frame.setSize(500, 500); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLocationRelativeTo(null); frame.add(new MouseMoveDemo()); frame.setVisible(true); frame.pack(); } @Override public void adjustmentValueChanged(AdjustmentEvent e) { JScrollBar temp = (JScrollBar) e.getSource(); if (temp == jsx) x = temp.getValue(); else if (temp == jsy) y = temp.getValue(); pane.repaint(); } public void mouseDragged(MouseEvent e) { int x = e.getX(); int y = e.getY(); if (!((x <= fx + 20) && (x >= fx - 20) && (y <= fy + 20) && (y >= fy - 20))) return; this.x = (int) (x / 300.0 * 100); this.y = (int) (y / 300.0 * 100); updateScroll(); pane.repaint(); } public void mouseMoved(MouseEvent e) { } private void updateScroll() { jsx.setValue(x); jsy.setValue(y); } class MyPanel extends JPanel { MyPanel() { this.setPreferredSize(new Dimension(340, 340)); // repaint(); } public void paint(Graphics g) { fx = (int) (x / 100.0 * 300); fy = (int) (y / 100.0 * 300); if (fx >= 280) fx = 280; if (fy >= 280) fy = 280; if (fx <= 20) fx = 20; if (fy <= 20) fy = 20; g.setColor(Color.BLACK); g.fillRect(0, 0, 300, 300); g.setColor(Color.BLUE); g.fillRect(fx - 20, fy - 20, 40, 40); } } }