我正在使用graphstream库,以便使用Java构建可视化图形应用程序。我想在从jframe扩展的类中加载图形。问题是我发现的documentation很旧,没有找到其他文档。 这是我代码的一部分,我要从现有文件中加载图形:
package tutographstream;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.io.FileReader;
import java.util.Scanner;
import javax.swing.JFrame;
import javax.swing.JPanel;
import org.graphstream.graph.Graph;
import org.graphstream.graph.Node;
import org.graphstream.graph.implementations.SingleGraph;
import org.graphstream.ui.swingViewer.ViewPanel;
import org.graphstream.ui.view.Viewer;
public class MainViewer extends JFrame{
Graph graph = null;
Viewer viewer = null;
public MainViewer(){
initComponents();
}
void initComponents(){
setDefaultCloseOperation(EXIT_ON_CLOSE);
Dimension DimMax = Toolkit.getDefaultToolkit().getScreenSize();
setMaximumSize(DimMax);
setExtendedState(JFrame.MAXIMIZED_BOTH);
graphViewerJPanel = new JPanel(new GridLayout()){
@Override
public Dimension getPreferredSize() {
return new Dimension(700, 700);
}
};
graphViewerJPanel.setBackground(Color.cyan);
add(graphViewerJPanel);
}
public Graph buildGraph(String filepath, int N){
double[][] mat = null;
try {
mat = new double[N][N];
Scanner sc = new Scanner(new FileReader(filepath));
int counter = 0;
while(sc.hasNext()){
mat[counter / N][counter % N] = Double.valueOf(sc.next());
counter++;
}
graph = new SingleGraph("Tutorial 1", false, true);
for(int i=0; i<N; i++) {
graph.addNode("A"+i);
}
for(int i=0; i<N; i++)
for(int j=i; j<N; j++)
if(mat[i][j] != 0)
graph.addEdge(""+(i*N+j), "A"+i, "A"+j);
int index=0;
for(Node node:graph.getNodeSet()){
node.addAttribute("ui.label", ""+index);
node.addAttribute("ui.style", "shape:circle; size:30px; text-alignment: center;");
index++;
}
} catch (Exception e) {
System.out.println("Error: "+e.getMessage());
}
return graph;
}
public Viewer loadGraph(String filepath, int N){
buildGraph(filepath, N);
if(graph != null){
viewer = new Viewer(graph, Viewer.ThreadingModel.GRAPH_IN_GUI_THREAD);
ViewPanel view_panel = viewer.addDefaultView(false);
viewer.enableAutoLayout();
graphViewerJPanel.add(view_panel);
repaint();
}
else
System.out.println(" Error");
return viewer;
}
//main function
public static void main(String[] args) {
int N = 20;
String filepath = "files/ErdosReney"+N+".txt";
MainViewer main_viewer = new MainViewer();
main_viewer.setVisible(true);
Viewer viewer = main_viewer.loadGraph(filepath, N);
}
//components
JPanel graphViewerJPanel;
}
问题在于该图形未显示在jpanel中。