Pergunta

Estou usando Jung ( http://jung.sourceforge.net/index.html ) desenhar gráficos em Java. O software é ótimo, mas tenho uma pequena pergunta. Como posso ter certeza de que o gráfico exibido é sempre o mesmo (nenhuma alteração é arquitetura ou posição)?

Para ser mais específico: o modelo de gráfico (dados a serem representados) não muda, mas sua representação muda cada vez que clico no botão "View Graph" :) [Alguns vértices estão em outros lugares, por exemplo: às vezes na parte superior da janela, às vezes na parte inferior

Obrigada,

Iulian

Foi útil?

Solução

UMA Staticlayout Permite especificar um vértice para Point2d transformador. Isso permitirá que você controla onde os vértices são colocados e devem fazer o que você deseja fazer. Você deve usar o seguinte construtor:

public StaticLayout(Graph<V,E> graph,
                org.apache.commons.collections15.Transformer<V,Point2D> initializer)

Você precisará implementar o seu próprio transformador Isso pega um vértice e retorna o local onde o vértice deve aparecer. Um exemplo de seu uso:

package test;

import java.awt.Dimension;
import java.awt.geom.Point2D;
import java.io.IOException;

import javax.swing.JFrame;

import org.apache.commons.collections15.Transformer;

import edu.uci.ics.jung.algorithms.layout.StaticLayout;
import edu.uci.ics.jung.graph.Graph;
import edu.uci.ics.jung.graph.SparseMultigraph;
import edu.uci.ics.jung.visualization.VisualizationViewer;

/**
 * Jung example - vertices appearing in same location
 * 
 * @author Kah
 */
public class StaticLocation {

    /**
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        // Setup the example graph.
        Graph<Integer, String> basis = new SparseMultigraph<Integer, String>();
        basis.addVertex(Integer.valueOf(0));
        basis.addVertex(Integer.valueOf(1));
        basis.addVertex(Integer.valueOf(2));
        basis.addEdge("Edge 1", Integer.valueOf(0), Integer.valueOf(1));
        basis.addEdge("Edge 2", Integer.valueOf(0), Integer.valueOf(2));
        basis.addEdge("Edge 3", Integer.valueOf(1), Integer.valueOf(2));

        Transformer<Integer, Point2D> locationTransformer = new Transformer<Integer, Point2D>() {

            @Override
            public Point2D transform(Integer vertex) {
                int value = (vertex.intValue() * 40) + 20;
                return new Point2D.Double((double) value, (double) value);
            }
        };

        StaticLayout<Integer, String> layout = new StaticLayout<Integer, String>(
                basis, locationTransformer);
        layout.setSize(new Dimension(250, 250));
        VisualizationViewer<Integer, String> vv = new VisualizationViewer<Integer, String>(
                layout);

        vv.setPreferredSize(new Dimension(250, 250));

        JFrame frame = new JFrame("Simple Graph View 2");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(vv);
        vv.setOpaque(false);
        frame.pack();
        frame.setVisible(true);
    }
}

Adicionado 20 de fevereiro de 2010:

Uma alternativa é usar um PersistentLayoutImpl Para salvar os locais dos vértices em um arquivo. No entanto, você também precisa persistir de alguma forma o gráfico para obter quais vértices e vértices estavam lá (isso precisa persistir separadamente). Há número de classes para persistir o gráfico em edu.uci.ics.jung.io. Este é um exemplo que usa apenas PersistentLayoutImpl:

package test;

import java.awt.Dimension;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import javax.swing.JFrame;

import org.apache.commons.collections15.Transformer;

import edu.uci.ics.jung.algorithms.layout.Layout;
import edu.uci.ics.jung.algorithms.layout.SpringLayout2;
import edu.uci.ics.jung.graph.Graph;
import edu.uci.ics.jung.graph.SparseMultigraph;
import edu.uci.ics.jung.io.GraphMLReader;
import edu.uci.ics.jung.io.GraphMLWriter;
import edu.uci.ics.jung.visualization.VisualizationViewer;
import edu.uci.ics.jung.visualization.decorators.ToStringLabeller;
import edu.uci.ics.jung.visualization.layout.PersistentLayoutImpl;

/**
 * Jung example - vertices appearing in same location
 * 
 * @author Kah
 */
public class PersistentVertices
{

    /**
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException
    {
        // Setup the example graph.
        try
        {
            VisualizationViewer<Integer, String> vv = new VisualizationViewer<Integer, String>(
                    getLayout());

            vv.setPreferredSize(new Dimension(250, 250));

            JFrame frame = new JFrame("Simple Graph View 2");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.getContentPane().add(vv);
            vv.setOpaque(false);
            frame.pack();
            frame.setVisible(true);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    private static Layout<Integer, String> getLayout() throws IOException,
            ClassNotFoundException
    {
        Graph<Integer, String> graph = new SparseMultigraph<Integer, String>();
        File source = new File("C:\\layout.dat");
        SpringLayout2<Integer, String> backing = new SpringLayout2<Integer, String>(
                graph);
        PersistentLayoutImpl<Integer, String> layout = new PersistentLayoutImpl<Integer, String>(
                backing);
        layout.setSize(new Dimension(250, 250));

        // Note that you also need to put the vertices and edges back before
        // restoring.
        graph.addVertex(Integer.valueOf(0));
        graph.addVertex(Integer.valueOf(1));
        graph.addVertex(Integer.valueOf(2));
        graph.addEdge("Edge 1", Integer.valueOf(0), Integer.valueOf(1));
        graph.addEdge("Edge 2", Integer.valueOf(0), Integer.valueOf(2));
        graph.addEdge("Edge 3", Integer.valueOf(1), Integer.valueOf(2));

        if (source.exists())
        {
            layout.restore(source.getAbsolutePath());
        }
        else
        {
            layout.persist(source.getAbsolutePath());
        }
        return layout;
    }
}

Observe que o exemplo ainda não persiste os vértices e arestas, pois não tive tempo para descobrir como usar as classes em edu.uci.ics.jung.io ainda.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top