这里有一个简单的代码向您展示如何缩放图表:
public class zoomGraph{
public zoomGraph(){
}
//the methode that will zoom the graph
public static void zoomGraphMouseWheelMoved(MouseWheelEvent mwe, ViewPanel view_panel){
if (Event.ALT_MASK != 0) {
if (mwe.getWheelRotation() > 0) {
double new_view_percent = view_panel.getCamera().getViewPercent() + 0.05;
view_panel.getCamera().setViewPercent(new_view_percent);
} else if (mwe.getWheelRotation() < 0) {
double current_view_percent = view_panel.getCamera().getViewPercent();
if(current_view_percent > 0.05){
view_panel.getCamera().setViewPercent(current_view_percent - 0.05);
}
}
}
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setLayout(new GridLayout());
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setBounds(0, 0, 700, 500);
frame.setPreferredSize(new Dimension(700, 500));
//Components
JPanel panel = new JPanel();
panel.setLayout(new GridLayout());
frame.add(panel);
//create a simple graph
Graph graph = new SingleGraph("tuto_zoom", false, true);
graph.addNode("node_1");
graph.addNode("node_2");
graph.addEdge("edge_1_2", "node_1","node_2");
//show the graph in the panel
Viewer viewer = new Viewer(graph, Viewer.ThreadingModel.GRAPH_IN_ANOTHER_THREAD);
viewer.enableAutoLayout();
ViewPanel view_panel = viewer.addDefaultView(false);
Rectangle rec = panel.getBounds();
view_panel.setBounds(0, 0, rec.width, rec.height);
view_panel.setPreferredSize(new Dimension(rec.width, rec.height));
panel.add(view_panel);
//add a mouse wheel listener to the ViewPanel for zooming the graph
view_panel.addMouseWheelListener(new MouseWheelListener() {
@Override
public void mouseWheelMoved(MouseWheelEvent mwe) {
zoomGraph.zoomGraphMouseWheelMoved(mwe, view_panel);
}
});
frame.setVisible(true);
}
}