0

Я хочу добавить новые вершины и ребра и создать граф, используя библиотеку JGraph. Я всегда получаю это java.lang.NullPointer исключение. Я создал функцию класса createvertex для создания новых ячеек/вершин и рисования границ моего подключения к портам. Но порт всегда отображается как null, даже если я не объявил его равным нулю. Ниже мой код. Что-то не так в моем коде?Добавление вершин, ребер и портов с помощью JGraph

public class HelloWorld { 

public static void main(String[] args) { 

    // Construct Model and Graph 
    GraphModel model = new DefaultGraphModel(); 
    GraphLayoutCache view= new GraphLayoutCache(model,new DefaultCellViewFactory()); 

    JGraph graph = new JGraph(model,view); 

    // Control-drag should clone selection 
    graph.setCloneable(true); 

    // Enable edit without final RETURN keystroke 
    graph.setInvokesStopCellEditing(true); 

    // When over a cell, jump to its default port (we only have one, anyway) 
    graph.setJumpToDefaultPort(true); 

    // Insert all three cells in one call, so we need an array to store them 
    DefaultGraphCell[] cells = new DefaultGraphCell[5]; 
    DefaultPort[] port = new DefaultPort[4]; 

    // Create Hello Vertex 
    cells[0] = createVertex("Hello", 20, 20, 40, 20, Color.BLACK, true); 

    port[0].setParent(cells[0]); 

    // Create World Vertex 
    cells[1] = createVertex("World", 140, 140, 40, 20, Color.ORANGE, true); 
    cells[1].add(port[1]); 
    cells[1].add(port[2]); 
    port[1].setParent(cells[1]); 
    port[2].setParent(cells[1]); 

    cells[3]= createVertex("Optical Cards",150,150,20,40,Color.GREEN, true); 
    cells[3].add(port[3]); 
    port[3].setParent(cells[3]); 


    // Create Edge 
    DefaultEdge[] edge = new DefaultEdge[2]; 

    // Fetch the ports from the new vertices, and connect them with the edge 
    edge[0].setSource(cells[0].getChildAt(0)); 
    edge[0].setTarget(cells[1].getChildAt(0)); 

    cells[2] = edge[0]; 

    edge[1].setSource(cells[1].getChildAt(1)); 
    edge[1].setTarget(cells[3].getChildAt(0)); 

    cells[4]=edge[1]; 

    // Set Arrow Style for edge 
    int arrow = GraphConstants.ARROW_CLASSIC; 
    GraphConstants.setLineEnd(edge[0].getAttributes(), arrow); 
    GraphConstants.setEndFill(edge[0].getAttributes(), true); 

    GraphConstants.setLineEnd(edge[1].getAttributes(), arrow); 
    GraphConstants.setEndFill(edge[1].getAttributes(), true); 

    // Insert the cells via the cache, so they get selected 
    graph.getGraphLayoutCache().insert(cells); 

    // Show in Frame 
    JFrame frame = new JFrame(); 
    frame.getContentPane().add(new JScrollPane(graph)); 
    //frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.pack(); 
    frame.setVisible(true); 
} 

public static DefaultGraphCell createVertex(String name, double x,double y,double w,double h, Color bg, boolean raised) { 

    // Create vertex with the given name 
    DefaultGraphCell cell = new DefaultGraphCell(name); 

    // Set bounds 
    GraphConstants.setBounds(cell.getAttributes(), new Rectangle2D.Double(
      x, y, w, h)); 

    // Set fill color 

     GraphConstants.setGradientColor(cell.getAttributes(), Color.orange); 
     GraphConstants.setOpaque(cell.getAttributes(), true); 

    // Set raised border 
    if (raised) 
     GraphConstants.setBorder(cell.getAttributes(), BorderFactory 
       .createRaisedBevelBorder()); 
    else 
     // Set black border 
     GraphConstants.setBorderColor(cell.getAttributes(), Color.black); 

    // Add a Port 
    DefaultPort port = new DefaultPort(); 
    cell.add(port); 

    return cell; 
} 
} 

ответ

0
DefaultPort[] port = new DefaultPort[4]; 




// Create Hello Vertex 
cells[0] = createVertex("Hello", 20, 20, 40, 20, Color.BLACK, true); 

port[0].setParent(cells[0]); // <---------- port[0] is null here, so you 
           //    cannot call setParent() 

Просто потому, что вы инициализации порта массив не означает, что вы можете просто использовать первый DefaultPort элемент в массиве. Вам нужно заполнить массив действительными, ненулевыми объектами DefaultPort, прежде чем пытаться разыменовать элемент в массиве.

+0

Можете ли вы объяснить, как это сделать? – span

 Смежные вопросы

  • Нет связанных вопросов^_^