1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
| public class TestDragScroll extends JFrame
{
public static class Panel extends JPanel implements MouseListener, MouseMotionListener
{
String imageStr = "/home/image.jpg";
File file = new File(imageStr);
BufferedImage buffImage;
int x = 0;
int y = 0;
public Panel() throws IOException
{
buffImage = ImageIO.read(file);
setPreferredSize(new Dimension(buffImage.getWidth(),buffImage.getHeight()));
addMouseListener(this);
addMouseMotionListener(this);
}
@Override
public void paint(Graphics g)
{
g.drawImage(buffImage, 0, 0, null);
}
@Override
public void mousePressed(MouseEvent e)
{
x = e.getX();
y = e.getY();
}
@Override
public void mouseReleased(MouseEvent e) {}
@Override
public void mouseDragged(MouseEvent e)
{
if (contains(e.getX(), e.getY()))
{
setLocation(getX() + e.getX() - x, getY() + e.getY() - y);
repaint();
}
}
@Override
public void mouseClicked(MouseEvent e){}
@Override
public void mouseMoved(MouseEvent e) {}
@Override
public void mouseEntered(MouseEvent e) {}
@Override
public void mouseExited(MouseEvent e) {}
}
Panel panel = new Panel();
JScrollPane scrollPane = new JScrollPane();
public TestDragScroll() throws IOException
{
setLayout(new BorderLayout());
scrollPane.setViewportView(panel);
add(scrollPane,BorderLayout.CENTER);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setBounds(0, 0, 800, 600);
setVisible(true);
}
public static void main(String[] args) throws IOException
{
TestDragScroll test = new TestDragScroll();
}
} |
Partager