Posted on 2007-04-26 11:54
G_G 阅读(511)
评论(0) 编辑 收藏 所属分类:
Swing
图象拖动(简单)
代码 上 哈 解释不多 !!!
^_^
package src.jframe;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import java.awt.Event;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.ArrayList;
public class MyFrame implements MouseListener,MouseMotionListener {
//图象集合
private ArrayList list = new ArrayList();
//当前 拖动 图象
private Rectangle re = null ;
private JFrame jf ;
{
jf = new JFrame(){
public void paint(Graphics g){
super.paint(g);
for(int i=0;i<list.size();i++){
Rectangle ne = (Rectangle)list.get(i);
this.getGraphics().drawRect(ne.x,ne.y,ne.height,ne.width);
System.out.println("ok");
}
}
};
jf.addWindowListener(new WindowListener(){
public void windowActivated(WindowEvent e) {
// TODO Auto-generated method stub
}
public void windowClosed(WindowEvent e) {
// TODO Auto-generated method stub
}
public void windowClosing(WindowEvent e) {
System.exit(0);
}
public void windowDeactivated(WindowEvent e) {
// TODO Auto-generated method stub
}
public void windowDeiconified(WindowEvent e) {
// TODO Auto-generated method stub
}
public void windowIconified(WindowEvent e) {
// TODO Auto-generated method stub
}
public void windowOpened(WindowEvent e) {
// TODO Auto-generated method stub
}
});
jf.setBounds(400,400,400,400);
jf.addMouseListener(this);
jf.addMouseMotionListener(this);
jf.setVisible(true);
}
public JFrame getFrame(){
return this.jf ;
}
//双击 花出图象
public void mouseClicked(MouseEvent e) {
if(e.getClickCount() == 2){
Point po = e.getPoint() ;
Rectangle ne = new Rectangle();
ne.setBounds((int)po.getX(),(int)po.getY(),20,20);
System.out.println("ko1");
addList(ne); //添加入 集合
}
}
private void addList(Rectangle ne) {
list.add(ne);
this.jf.repaint();
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
// 拖动选取
public void mousePressed(MouseEvent e) {
this.re = null ;
for(int i=0;i<this.list.size();i++){
Rectangle re = (Rectangle)list.get(i);
if( re.contains((int)e.getX(),(int)e.getY()) ){
this.re = re;
}
}
}
public void mouseReleased(MouseEvent e) {
}
//关键 拖动 ***********************
public void mouseDragged(MouseEvent e) {
if(this.re != null){
this.re.setBounds((int)e.getX(),(int)e.getY(),20,20);
this.jf.repaint();
}
}
public void mouseMoved(MouseEvent e) {
}
public static void main(String[]args){
JFrame jf = (new MyFrame()).getFrame();
}
}
图象的缩放Graphics2D *******
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D)g;
double bh = fh / 1200 ;
double bw = fw / 600;
g2d.scale(bh,bw);
getDisplayUpdate().draw(g2d, this);
this.setBackground(this.getBg());
}