Arrastar Icone com o mouse?

3 respostas
R

fala galera, tô com uma duvida aki, tô fazendo um trabalho de grafos e preciso adicionar um vertice na tela
até ae tudo bem, mas preciso arrastar o vertice na tela, ae não consigo, alguem pode me ajudar, agradeço a todos

3 Respostas

R

vou postar o código, só um minuto… :slight_smile:

R
public class PainelDoGrafo extends JPanel {
       
	private static final long serialVersionUID = 1L;
		private Grafos grafo;
        private HashMap<Vértice, Point2D> hash;
        private HashMap<Vértice, Boolean> hashB = new HashMap<Vértice, Boolean>();
        private static final Double RAIODOVÉRTICE = 11.9;
        private static final Double ÂNGULOINICIAL = -Math.PI/1;
       
        public PainelDoGrafo(Grafos grafo) {
                this.grafo = grafo;
                
                Collection<Vértice> vértices = grafo.vértices();
                Iterator<Vértice> iterator = vértices.iterator();
                while (iterator.hasNext()) {
                        Vértice vertice = iterator.next();
                        adicionaVértice(vertice);
                }
                conectaVértices();

                addMouseListener(new TratadorDoGrafo(this));
        }

    public void paint(Graphics g) {
    	
        Graphics2D g2d = (Graphics2D) g;
        Point centro = new Point(getWidth()/2, getHeight()/2);
        Double raio = Math.min(getWidth()/3.0, getHeight()/3.0) - 2 * RAIODOVÉRTICE;
       
        hash = new HashMap<Vértice, Point2D>();
       
        int i = 0;
        for (Vértice v : grafo.vértices()) {
                Double xCentro = centro.x + raio * Math.cos(Math.PI * 2 * i / grafo.ordem() + ÂNGULOINICIAL);
                Double yCentro = centro.y + raio * Math.sin(Math.PI * 2 * i / grafo.ordem() + ÂNGULOINICIAL);
                
            hash.put(v, new Point2D.Double(xCentro, yCentro));
            Double x = xCentro  - RAIODOVÉRTICE;
            Double y = yCentro  - RAIODOVÉRTICE;
           
            if (hashB.get(v).booleanValue()) {
                                g2d.setColor(Color.RED);
                        }
           
            g2d.draw(new Ellipse2D.Double(x, y, RAIODOVÉRTICE * 2, RAIODOVÉRTICE * 2));
           
            g2d.setColor(Color.black);
           
            g2d.drawString(v.getNome(), xCentro.intValue(), yCentro.intValue());
           
            i++;
        }
       
        for (Aresta a : grafo.arestas()) {
                Double x1, y1, x2,y2, difX, difY, ângulo;
            x1 = hash.get(a.um()).getX();
            y1 = hash.get(a.um()).getY();
            x2 = hash.get(a.dois()).getX();
            y2 = hash.get(a.dois()).getY();
            difX = x2 - x1;
            difY = y2 - y1;
            ângulo = Math.atan(difY/difX);
            if (x1>x2) {
                    ângulo += Math.PI;
            }
            x1 = x1 + RAIODOVÉRTICE * Math.cos(ângulo);
            y1 = y1 + RAIODOVÉRTICE * Math.sin(ângulo);
            x2 = x2 - RAIODOVÉRTICE * Math.cos(ângulo);
            y2 = y2 - RAIODOVÉRTICE * Math.sin(ângulo);
           
            g2d.draw(new Line2D.Double(x1, y1, x2, y2));
        }
           
    }
       
        public void adicionaVértice(Vértice v) {
                grafo.adicionaVértice(v);
                hashB.put(v, new Boolean(false));
        }
       
        public void removerVértices() {
                for (Vértice v : hash.keySet()) {
                        if (hashB.get(v)) {
                                grafo.removeVértice(v);
                                hashB.remove(v);
                        }
                }
        }

        public void conectaVértices() {
                for (Vértice v1 : hashB.keySet()) {
                        if (hashB.get(v1).booleanValue()) {
                                for (Vértice v2 : hashB.keySet()) {
                                        if (hashB.get(v2).booleanValue()&&(v2 != v1)) {
                                                grafo.conectaVértices(v1, v2);
                                        }
                                }
                        }
                }
        }

        public void desconectaVértices() {
                for (Vértice v1 : hashB.keySet()) {
                        if (hashB.get(v1)) {
                                for (Vértice v2 : hashB.keySet()) {
                                        if (hashB.get(v2)&&(v2 != v1)) {
                                                grafo.desconectaVértices(v1, v2);
                                        }
                                }
                        }
                }
        }
       
        public void clique(Point p) {
                for (Vértice v : hash.keySet()) {
                        if (hash.get(v).distance(new Point2D.Double(p.x, p.y)) <= RAIODOVÉRTICE) {
                                Boolean b = !hashB.get(v).booleanValue();
                                hashB.put(v, b);
                        }
                }
                paint(getGraphics());
        }      
}
public class JanelaTela extends JFrame implements ActionListener{

	private static final long serialVersionUID = 1L;
	private JButton btConectar, btDesconectar, btAdicionar, btRemover, btCancelar;
	private JButton btCompletarGrafo, btGrafoÉCompleto, btGrafoÉArvore, btBuscaLargura, btVerticesPendentes;
	private JLabel lbNomeVertice, lbLinhaCima, lbLinhaBaixo;
	private JTextField txNomeVertice;
	private JPanel pnSul, pnNorte, pnCentro;
	private Grafos grafo;
	private Vértice v;
    private PainelDoGrafo painelDoGrafo;
    private String situacao1 = "";
    private String situacao2 = "";
	private int situacao3;
	private String situacao4 = "";
	
	
	public JanelaTela(Grafos grafo){
		this.grafo = grafo;
		
		setTitle("Teoria dos Grafos");
		setSize(800, 700);
		// PAINEL NORTE DA TELA
		pnNorte = new JPanel();
		pnNorte.setLayout(null);
		pnNorte.setBounds(0,0, 820, 70);
		pnNorte.setBackground(Color.LIGHT_GRAY);
		// PAINEL SUL DA TELA
		pnSul = new JPanel();
		pnSul.setLayout(null);
		pnSul.setBounds(0, 600, 820, 100);
		pnSul.setBackground(Color.lightGray);
		// PAINEL CENTRAL DA TELA
		pnCentro = new JPanel();
		pnCentro.setLayout(new BorderLayout());
		//CONSTROI AS JLABEL DOS PAINEIS
		lbNomeVertice = new JLabel("Nome do vértice:");
		lbNomeVertice.setBounds(310, 10, 150, 20);
		lbLinhaCima= new JLabel("=================================================================================================================");
		lbLinhaCima.setBounds(0, 60, 800, 10);
		lbLinhaBaixo= new JLabel("=================================================================================================================");
		lbLinhaBaixo.setBounds(0, 5, 800, 10);
		// ADICIONA AS JLABEL NOS PAINEIS
		pnSul.add(lbLinhaBaixo);
		pnNorte.add(lbLinhaCima);
		pnNorte.add(lbNomeVertice);
		//CONTROI OS JTEXTFIELD
		txNomeVertice= new JTextField();
		txNomeVertice.setBounds(410, 10, 50, 20);
		//ADICIONA O JTEXTFIELD NO PAINEL
		pnNorte.add(txNomeVertice);
		//CONTROI OS BOTÕES
		btAdicionar = new JButton(" Adicionar ");
		btAdicionar.setBounds(5, 35, 150, 20);
		btRemover = new JButton(" Remover ");
		btRemover.setBounds(160, 35, 150, 20);
		btConectar = new JButton(" Conectar ");
		btConectar.setBounds(315, 35, 150, 20);
		btDesconectar = new JButton(" Desconectar ");
		btDesconectar.setBounds(470, 35, 150, 20);
		btCancelar = new JButton(" Sair ");
		btCancelar.setBounds(625, 35, 150, 20);
		//ADICIONA OS BOTÕES NOS PAINEIS
		pnNorte.add(btCancelar);
		pnNorte.add(btAdicionar);
		pnNorte.add(btRemover);
		pnNorte.add(btConectar);
		pnNorte.add(btDesconectar);
		// CONSTROI MAIS BOTÕES
		btGrafoÉCompleto = new JButton(" Grafo Completo ");
		btGrafoÉCompleto.setBounds(5, 20, 150, 20);
		btGrafoÉArvore = new JButton(" Grafo árvore ");
		btGrafoÉArvore.setBounds(160, 20, 150, 20);
		btVerticesPendentes = new JButton(" Vértices pendentes ");
		btVerticesPendentes.setBounds(315, 20, 151, 20);
		btBuscaLargura = new JButton(" Busca em largura ");
		btBuscaLargura.setBounds(470, 20, 150, 20);
		btCompletarGrafo = new JButton(" Completar grafo ");
		btCompletarGrafo.setBounds(625, 20, 150, 20);
		//ADICIONA OS BOTÕES NOVAMENTE
		pnSul.add(btGrafoÉCompleto);
		pnSul.add(btGrafoÉArvore);
		pnSul.add(btVerticesPendentes);
		pnSul.add(btBuscaLargura);
		pnSul.add(btCompletarGrafo);
				
		// ADICIONA OS PAINEIS NA FRAME
		getContentPane().add(pnNorte);
		getContentPane().add(pnSul);
		getContentPane().add(pnCentro);
		//CONSTROI O PAINEL PARA INSERIR O GRAFOS
		painelDoGrafo = new PainelDoGrafo(grafo);
		//ADICIONA O GRAFO NO PAINEL
		pnCentro.add(painelDoGrafo);
		//TRATA OS EVENTOS DOS BOTÕES
		btAdicionar.addMouseListener(new TratadorDoBotãoAdicionar(this));
		btRemover.addMouseListener(new TratadorDoBotãoRemover(this));
		btConectar.addMouseListener(new TratadorDoBotãoConectar(this));
		btDesconectar.addMouseListener(new TratadorDoBotãoDesconectar(this));
		btCompletarGrafo.addMouseListener(new TratadorDoBotãoCompletarOGrafo(this));
		btGrafoÉCompleto.addActionListener(this);
		btGrafoÉArvore.addActionListener(this);
		btBuscaLargura.addActionListener(this);
		btVerticesPendentes.addActionListener(this);
		btCancelar.addActionListener(this);
		
		
	}
	
	public void actionPerformed(ActionEvent acao) {
		if (acao.getSource()== btGrafoÉCompleto){
			grafoCompleto();
			
		}
		else if (acao.getSource()== btGrafoÉArvore){
			grafoArvore();
		}
		else if(acao.getSource()== btBuscaLargura){
			buscaLargura();
		}
		else if (acao.getSource()==btVerticesPendentes){
			verticesPendentes();
			
		}
		else if (acao.getSource()== btCancelar){
			System.exit(0);
		}
		
	}
	public void verticesPendentes(){
		try{
			situacao3   = grafo.grau(v);
			JOptionPane.showMessageDialog( null , " "+ situacao3 , " Situação do grafo",
					JOptionPane.INFORMATION_MESSAGE );
			atualizar();
		}catch(Exception e){
    		JOptionPane.showMessageDialog( this, "Ocorreu um erro!!! " + e.getLocalizedMessage());    		
    	}
	}
	public void buscaLargura(){
		situacao4   = "";
		JOptionPane.showMessageDialog( null , " "+ situacao4 , " Situação do grafo",
				JOptionPane.INFORMATION_MESSAGE );
		atualizar();

	}
	public void grafoArvore(){
		situacao1 = grafo.éÁrvore();
		JOptionPane.showMessageDialog( null , " "+ situacao1, " Situação do grafo",
				JOptionPane.INFORMATION_MESSAGE ); 
		atualizar();		
	}
	
	public void grafoCompleto(){
		
		situacao2 = grafo.éCompleto();
		JOptionPane.showMessageDialog( null , " "+ situacao2, " Situação do grafo",
				JOptionPane.INFORMATION_MESSAGE ); 
		atualizar();
		
		}
	
	 public void adicionaVértice() {
         painelDoGrafo.adicionaVértice(new Vértice(txNomeVertice.getText()));
         atualizar();
         txNomeVertice.setText("");
         }

     public void removeVértices() {
         painelDoGrafo.removerVértices();
         atualizar();
         }

     public void conectaVértices() {
         painelDoGrafo.conectaVértices();
         atualizar();
         }

     public void desconectaVértices() {
         painelDoGrafo.desconectaVértices();
         atualizar();
         }

     private void atualizar() {
         paint(getGraphics());
         }
 	
	public static void main(String[] args) {
		Metro metro = new Metro();
		JanelaTela tl = new JanelaTela(metro);
		tl.setVisible(true);
		tl.setLocationRelativeTo(null);
		tl.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
}
R

tenho mais classes de eventos do mouse, se precisarem… obrigado

Criado 14 de junho de 2013
Ultima resposta 14 de jun. de 2013
Respostas 3
Participantes 1