疯狂java


您现在的位置: 疯狂软件 >> 新闻资讯 >> 正文

如何用java实现图片的拖动以查看全部


 

  import java.awt.Color;

  import java.awt.event.MouseAdapter;

  import java.awt.event.MouseEvent;

  import java.awt.event.MouseMotionListener;

  import javax.swing.BorderFactory;

  import javax.swing.Icon;

  import javax.swing.ImageIcon;

  import javax.swing.JFrame;

  import javax.swing.JLabel;

  public class TestMoveImage {

  static int x,y;

  private static int num=0;

  private static Icon icon=null;

  public static void main(String[] args) throws Exception{

  JFrame f = new JFrame();

  f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

  f.getContentPane().setLayout(null);//这个要设置成 null

  //图片

  icon = new ImageIcon("dog.jpg"); //注:用斜杆系统会默认帮你转化为反斜杠,如果要用反斜杠则要写成:F:\1353411350203.jpg

  JLabel l = new JLabel(icon); //创建具有指定图像的 JLabel 实例。

  l.setSize(icon.getIconWidth(),icon.getIconHeight());//设置面板的宽度和高度

  l.setBorder(BorderFactory.createLineBorder(Color.red));//给图片加上红色外框

  f.getContentPane().add(l);

  f.setSize(180,180);

  f.setVisible(true);

  l.addMouseListener(new MouseAdapter(){

  public void mousePressed(MouseEvent e){

  x=e.getX();

  y=e.getY();

  }

  });

  l.addMouseMotionListener(new MouseMotionListener(){

  public void mouseDragged(MouseEvent e) {

  JLabel l = (JLabel)e.getSource();

  l.setLocation(l.getX()+e.getX()-x,l.getY()+e.getY()-y);

  }

  public void mouseMoved(MouseEvent e) {}

  });

  }

  }