Results 1 to 2 of 2
Like Tree1Likes
  • 1 Post By KevinWorkman

Thread: how to mouve image with mouse

  1. #1
    mimiSoSO is offline Member
    Join Date
    May 2012
    Posts
    1
    Rep Power
    0

    Default how to mouve image with mouse

    hi,
    I have a big problem, i cant mouve image in my canvace, my code is zero error but i cant have the best result , my code about TSP(transport salesman problem), it is a simulator from internet network.
    my code :
    Java Code:
    import java.applet.*;
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.lang.reflect.*;
    import java.util.*;
    import java.applet.Applet ;
    
    import java.awt.BorderLayout;
    import java.awt.Graphics;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseMotionListener;
    
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.SwingConstants;
    import java.awt.image.*;
    public class essai extends Applet implements MouseListener, MouseMotionListener{
    
           double xa, yb;
           boolean dragging;
           boolean dragRedSquare;
           double offsetX, offsetY;
           //-------
           boolean NoeudVisitee,AgentFourmi,QtePhero;
    	   String sauv_res_cycl="nombre de cycle     bonne chemain\n";
    	   tsp myTsp;
    	   colony myColony;
    	   double averages[];
    	   TextField textNoeud,textAlpha,textBeta,textAnt,textVrate,textAmount,textRounds;
    	   Label labelBestPath;
    	   Button buttonGenerate,buttonGo;
    	   Image ord;
    
    public void init() {
    	    xa = 10;
            yb = 10;
            setBackground(Color.lightGray);
            addMouseListener(this);
            addMouseMotionListener(this);
              //---------
            NoeudVisitee = false;
    		AgentFourmi = false;
    		QtePhero = false;
    		MediaTracker mt= new MediaTracker(this);
    		ord = getImage(getCodeBase(),"ord1.jpg");
    		mt.addImage(ord,0);
            //Panel stat_cyc=new Panel();
    		Panel panelRight = new Panel(new GridLayout(15, 2, 4, 4));
    		BorderLayout bl = new BorderLayout();
    		//bl.setVgap(4);
    		Panel panelLeft = new Panel(bl);
    		Label labelNoeud = new Label("Noeud", Label.RIGHT);
    		Label labelAnt = new Label("Fourmi", Label.RIGHT);
    		Label labelVrate = new Label("Evaporation", Label.RIGHT);
    		Label labelAmount = new Label("Pheromone", Label.RIGHT);
    		Label labelRounds = new Label("Cycle", Label.RIGHT);
    		Label labelAlpha = new Label("Alpha", Label.RIGHT);
    	    Label labelBeta = new Label("Beta", Label.RIGHT);
    		labelBestPath = new Label("0.0", Label.CENTER);
    		labelBestPath.setBackground(Color.red);
    		textNoeud = new TextField("5", 6);
    		textAnt =  new TextField("1", 6);
    		textVrate = new TextField("0.5", 6);
    		textAmount = new TextField("1", 6);
    		textRounds = new TextField("40", 6);
    		textAlpha = new TextField("1", 6);
    		textBeta = new TextField("5", 6);
    		buttonGenerate = new Button("Generer");
    		buttonGo = new Button("Demarrer!");
    		buttonGo.setEnabled(false);
    		buttonGenerate.addActionListener(new buttonAL());
    		buttonGo.addActionListener(new buttonAL());
    		panelRight.add(labelNoeud); 			panelRight.add(textNoeud);
    		panelRight.add(labelAnt);				panelRight.add(textAnt);
    		panelRight.add(labelVrate);				panelRight.add(textVrate);
    		panelRight.add(labelAmount);			panelRight.add(textAmount);
    		panelRight.add(labelRounds);			panelRight.add(textRounds);
    		panelRight.add(labelAlpha); 			panelRight.add(textAlpha);
    		panelRight.add(labelBeta); 				panelRight.add(textBeta);
    		panelRight.add(new Label()); 			panelRight.add(buttonGenerate);
    		panelRight.add(new Label()); 			panelRight.add(buttonGo);
    		panelRight.add(new Label("MeilleurTrajet", Label.RIGHT));
    		panelRight.add(labelBestPath);
    		Panel panelMain = new Panel();
    		panelMain.add(panelLeft);
    		panelMain.add(panelRight);
    		Panel panelTop = new Panel(new BorderLayout());
    		panelTop.add("Center", panelMain);
    		setBackground(new Color (30,210,242));
    		add(panelTop);
             //---------
           }
    public void mousePressed(MouseEvent evt) {
              if (dragging)
                 return;
    
              double x=evt.getX();
              double y= evt.getY();
              if (x >= xa && y >= yb ) {
                 dragging = true;
                 dragRedSquare = true;
                 offsetX = x - xa;
                 offsetY = y - yb;
               }
    
              System.out.println("PRESSED");
              repaint();
              this.update(this.getGraphics());
           }
    public void mouseReleased(MouseEvent evt) {
               dragging = false;
               System.out.println("released");
               repaint();
               this.update(this.getGraphics());
           }
    public void mouseDragged(MouseEvent evt) {
               if (dragging == false)
                 return;
               int x = evt.getX();
               int y = evt.getY();
               if (dragRedSquare) {
                  xa = x - offsetX;
                  yb = y - offsetY;
               }
               System.out.println("dragged");
               repaint();
               this.update(this.getGraphics());
           }
    public void mouseMoved(MouseEvent evt) { }
    public void mouseClicked(MouseEvent evt) { }
    public void mouseEntered(MouseEvent evt) { }
    public void mouseExited(MouseEvent evt) { }
           //-------
    class buttonAL implements ActionListener {
    		public void actionPerformed(ActionEvent e) {
    			if (e.getActionCommand() == "Demarrer!") {
    				labelBestPath.setBackground(Color.blue);
    				int n = Integer.parseInt( textRounds.getText() );
    				int next_nbr_round=n+1;
    				String nouv_round="";
    				averages = new double[n];
    				for(int i = 0; i < n; i++)
    				averages[i] = myColony.runOneCycle();
    				labelBestPath.setBackground(Color.yellow);
    				AgentFourmi = true;
    				labelBestPath.setText( Double.toString(
    				Math.rint( myColony.bestLength*10000 ) / 10000) );
    				paint(getGraphics());
    			}
    
    			if (e.getActionCommand() == "Generer") {
    				myTsp = new tsp();
    				long t = (new Date()).getTime();
    
    				myTsp.GenererNoeud(Integer.parseInt(textNoeud.getText()), t);
    				myColony = new colony(Integer.parseInt(textAnt.getText()),1,1,myTsp);
    				NoeudVisitee = true;
    				paint(getGraphics());
    				buttonGo.setEnabled(true);
    
    			}
    
    
    
    		}
    	}
    public void paint (Graphics g2) {
      	    super.paintComponents(g2);
            Graphics2D g = (Graphics2D)g2;
            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
      	    addMouseListener(this);
            addMouseMotionListener(this);
            int w = getSize().width,h = getSize().height;
    	    g.fillRect(0, 0, w, h);
    			if (!NoeudVisitee) return;
    			int n = myTsp.getNbreN();
    			g.setColor(Color.red);
    			for(int i = 0; i < n; i++) {g.drawImage(ord,(int)(myTsp.Noeud[i].x * w - 1),(int)(myTsp.Noeud[i].y * h - 1),this);}
    			System.out.println("on repeint le panel");
    			//for(int i = 0; i < n; i++) {g.fill3DRect((int)(myTsp.Noeud[i].x * w - 1),(int)(myTsp.Noeud[i].y * h - 1), 3, 3, true);}
    			if (QtePhero) {
    				double minV = Double.MAX_VALUE, maxV = Double.MIN_VALUE;
    				for(int i = 0; i < n-1; i++)
    					for(int j = i+1; j < n; j++) {
    						if (minV > myColony.phMat[i][j])
    						  minV = myColony.phMat[i][j];
    						if (maxV < myColony.phMat[i][j])
    					      maxV = myColony.phMat[i][j];
    					}
    				double s = maxV - minV;
    				for(int i = 0; i < n-1; i++)
    					for(int j = i+1; j < n; j++) {
    						float t = (float)((myColony.phMat[i][j] - minV) / s);
    						g.setColor(new Color(t, t, t));
    						int x1 = (int)(myTsp.Noeud[i].x * w);
    						int y1 = (int)(myTsp.Noeud[i].y * h);
    						int x2 = (int)(myTsp.Noeud[j].x * w);
    						int y2 = (int)(myTsp.Noeud[j].y * h);
    						g.drawLine(x1, y1, x2, y2);
    					}
    				g.setColor(Color.yellow);
    				//for(int i = 0; i < n; i++) {g.fill3DRect((int)(myTsp.Noeud[i].x * w - 1),(int)(myTsp.Noeud[i].y * h - 1), 3, 3, true);}
    				for(int i = 0; i < n; i++) {g.drawImage(ord,(int)(myTsp.Noeud[i].x * w - 1),(int)(myTsp.Noeud[i].y * h - 1),this);}
    				repaint();
    				return;
    			}
    			if (!AgentFourmi) return;
    			g.setColor(Color.white);
    			for(int i = 0; i < n - 1; i++) {
    				int c1 = myColony.bestPath[i];
    				int c2 = myColony.bestPath[i+1];
    				int x1 = (int)(myTsp.Noeud[c1].x * w);
    				int y1 = (int)(myTsp.Noeud[c1].y * h);
    				int x2 = (int)(myTsp.Noeud[c2].x * w);
    				int y2 = (int)(myTsp.Noeud[c2].y * h);
    				g.drawLine(x1, y1, x2, y2);
    			}
    			int c1 = myColony.bestPath[n-1];
    			int c2 = myColony.bestPath[0];
    			int x1 = (int)(myTsp.Noeud[c1].x * w);
            	int y1 = (int)(myTsp.Noeud[c1].y * h);
    			int x2 = (int)(myTsp.Noeud[c2].x * w);
    			int y2 = (int)(myTsp.Noeud[c2].y * h);
    			g.drawLine(x1, y1, x2, y2);
    
       }
    public void update(Graphics g2) // to stop refresh flickering
        {
            paint(g2);
        }
    
    
        } // end class DragTwoSquares
    
    
           //______
    
    
    class tsp {
    
    	int NbreN; // nombre des noeuds
    	public node Noeud[]; // tableau  contenant les noeuds de type node
    	double distMat[][]; // distance entre les noeuds (matrice)
    	public int getNbreN() { return NbreN; }
    
    	//**** classe caractérise un noeud****
    	public class node {
    
    
    	    double x, y; // x est l'absisse du noeud, y est l'ordonné
    
    		public node(double a, double b) { x = a; y = b; }
    		public void setX(double t) { x = t; }
    		public void setY(double t) { y = t; }
    		public double getX() { return x; }
    		public double getY() { return y; }
    
    
    	}
    
    
    	// générer un ensemble des noeuds aléatoir
    
    	public void GenererNoeud(int n, long s) {
    		NbreN = n;
    		Random r = new Random(s);
    		Noeud = new node[n];
    		for(int i = 0; i < n; i++) {
    			Noeud[i] = new node(r.nextDouble(), r.nextDouble());
    
    		}
    		determineDistMat();
    
    
    	}
    
    
        // ***calculer la distance entre 2 points***
    	public double dist(int i, int j) {
    		double t1 = Noeud[i].getX() - Noeud[j].getX(),
    			   t2 = Noeud[i].getY() - Noeud[j].getY();
    		return Math.sqrt(t1*t1 + t2*t2);
    	}
    
    	// ***créer la matrice qui contient les distances entre les noeuds***
    	public void determineDistMat() {
    		distMat = new double[NbreN][NbreN];
    		for(int i = 0; i < NbreN; i++)
    			for(int j = i; j < NbreN; j++) {
    				distMat[i][j] = dist(i, j);
    				distMat[j][i] = dist(j, i);
    			}
    	}
    
    
    
    	//----------------------------------------
    	public double pathLength(int p[]) {// longeur de chemin
    
    		double t = 0;
    		for(int i = 0; i < NbreN - 1; i++)
    			t += dist(p[i], p[i+1]);
    		t += dist(p[NbreN-1], p[0]);
    		return t;
    	}
    	//----------------------------------------
    	public double getDist(int i, int j) {
    		return distMat[i][j];
    	}
    }
    
    class colony {
    	public double phMat[][];
    	double phAmt; // pheromone sur les arcs
    
    	public int controlAnt;
    	public int bestPath[];
    	public double bestLength;
    
    	public ant myAnts[];
    	tsp myTsp;
    	int na; // nombre de Fourmis
    	double vRate; // taux de vaporisation
    	Random rg;
    
    	//**** calsse Fourmi*****
    	class	ant {
    		public int path[], mark[]; // caractèristique du fourmi tableau liste des noeud visité,path = les chemins
    		int noeudActuel;
    		double traveledLength;
    		public String ListeVisite[];
    
    		// *****constructeur de la classe ant*****
    		public ant(int n) {
    			mark = new int[n];
    			path = new int[n];
    			ListeVisite= new String[n];
    		}
    		//*******fin de constructeur*****
    
    		public double calculateTraveledLength()
    		 {
    			traveledLength = myTsp.pathLength(path);
    			return traveledLength;
    		}
    
    		public double getTraveledLength()
    		{ return traveledLength; }
    
    
    
    		public void reset() {
    			noeudActuel =0;
    			path[0] = 0; // commencer au noeud[0]
    			for(int i = 0; i < myTsp.getNbreN(); i++)
    			mark[i] = 0;
    			mark[0] = 1; // noeud[0]a été visitée
    		}
    
    		//----------------------------------------
    		public void determineNextNoeud() {
    			int n = myTsp.getNbreN();
    			int countCandi = 0;// compteur
    			double alpha=0.5 , beta=0.3;
    			int[] candidate = new int[n];
    			double[] prCandi = new double[n];
    			for(int i = 0; i < n; i++) {
    				if (mark[i] == 0) {
    					candidate[countCandi] = i;// tableau des noeud non visité
    
    					prCandi[countCandi] = Math.pow(phMat[ path[noeudActuel] ][i],alpha) /
    																Math.pow(myTsp.getDist( path[noeudActuel], i ),beta);
    					++countCandi;// compteur des noeuds non visités
    				}
    			}
    
    			double s = 0;
    			for(int i = 0; i < countCandi; i++)
    				s += prCandi[i];
    			for(int i = 0; i < countCandi; i++)
    				prCandi[i] /= s;
    				// probabilité à choi
    
    			double hit = rg.nextDouble(),
    						 t = prCandi[0];
    			int w = 0;
    			for(w = 0; w < countCandi - 1; w++) {
    				if (t > hit) break;
    				t += prCandi[w + 1];
    			}
    			++noeudActuel;
    			path[noeudActuel] = candidate[w];
    			mark[ candidate[w] ] = 1;
    		}
    	}
    	//******fin de la classe Fourmi*******
    
    // constructeur de la classe colony
    	public colony(int n, double t, double p, tsp s) {
    		na = n; //nombre des Fourmi
    		vRate = t;
    		phAmt = p;
    		myTsp = s;
    		bestLength = Double.MAX_VALUE;
    
    		bestPath = new int[myTsp.getNbreN()];
    		phMat = new double[myTsp.getNbreN()][myTsp.getNbreN()];
    		myAnts = new ant[n];
    		rg = new Random();
    		for(int i = 0; i < n; i++)
    			myAnts[i] = new ant(myTsp.getNbreN());
    		for(int i = 0; i < myTsp.getNbreN(); i++)
    			for(int j = 0; j < myTsp.getNbreN(); j++) {
    				phMat[i][j] = 1;
    				phMat[j][i] = 1;
    			}
    	}
    	//----------------------------------------
    	public void runOneAnt(int x) {
    		int i=0 , j=0 ;
    		myAnts[x].reset();
    		if (myTsp.distMat[i][j] < 2) // condition ne fonctionne pas !!
    		{for(int k = 0; k < myTsp.getNbreN() - 1; k++)
    		  myAnts[x].determineNextNoeud();
    
    		  myAnts[x].calculateTraveledLength();
    	}}
    	//----------------------------------------
    	public double runOneCycle() {
    		for(int i = 0; i < na; i++)
    			runOneAnt(i);
    		return updatePhMat();
    	}
    	//----------------------------------------
    	public double updatePhMat() {
    		int n = Array.getLength( myAnts );
    		int m = myTsp.getNbreN();
    
    		controlAnt = -1;
    
    		for(int j = 0; j < myTsp.getNbreN(); j++)
    			for(int k = 0; k < myTsp.getNbreN(); k++)
    				phMat[j][k] *= vRate;
    
    		for(int i = 0; i < n; i++) {
    			double t = myAnts[i].getTraveledLength();
    
    			if (t < bestLength) {
    				controlAnt = i;// plusieur Fourmi
    				bestLength = t;
    				for(int j = 0; j < m; j++)
    					bestPath[j] = myAnts[i].path[j];
    			}
    
    			for(int j = 0; j < m - 1; j++) {
    				phMat[ myAnts[i].path[j] ][ myAnts[i].path[j+1] ] += phAmt / t;
    				phMat[ myAnts[i].path[j+1] ][ myAnts[i].path[j] ] += phAmt / t;
    			}
    
    		}
    
    
    
    
    
    		return bestLength;
    
    	}
    }

  2. #2
    KevinWorkman's Avatar
    KevinWorkman is offline Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    3,965
    Rep Power
    8

    Default Re: how to mouve image with mouse

    That is way too much code to ask strangers to debug for you, for free, in their spare time. If your question is about moving an image, your code should contain just the logic required to move an image- not any of that extra simulation code you included. Better to post an SSCCE than hundreds of lines of unrelated code.
    DarrylBurke likes this.
    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

Similar Threads

  1. Image Rotating Around Mouse
    By altosaxplayer88 in forum Java 2D
    Replies: 2
    Last Post: 06-01-2011, 02:36 AM
  2. Check if image contains mouse
    By trishtren in forum Java 2D
    Replies: 2
    Last Post: 05-15-2011, 10:49 PM
  3. how to move an image automatically without using mouse
    By saranyabaskaran in forum New To Java
    Replies: 6
    Last Post: 03-19-2011, 10:00 AM
  4. Mouse Event + Image Thresholding
    By ojmayolebron in forum AWT / Swing
    Replies: 0
    Last Post: 03-27-2009, 12:17 AM
  5. Image cropping in Jsf on the release of mouse
    By HarshalAuro in forum JavaServer Faces (JSF)
    Replies: 0
    Last Post: 11-12-2008, 06:24 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •