2011-03-16 2 views
1

Мне нужно создать апплет, где пользователь создает узлы, а затем создает ребра между ними.java апплет для создания графиков

Тогда я могу запустить свой алгоритм для обработки на этих узлах.

Однако я сталкиваюсь с проблемами в создании этого и хотел бы знать, существуют ли какие-то хорошие ссылки, которые по сути говорят мне, как подойти и создать апплет.

Есть хорошие учебники для создания апплета, но может любой из вас предложить, где они выглядят более в создании GUI (узлов) внутри и перемещая их вокруг .....

Большое спасибо ...

+2

Вы проверили ** JUNG 2.0 Framework **? Он может создавать граф узлов или в апплете или приложении Java [link] (http://jung.sourceforge.net/) – eee

+0

@ link-eee Я хотел бы сделать это полностью самостоятельно, если это возможно ... Итак спасибо за ваше предложение, но я хотел бы узнать, как я могу это сделать, просто используя стандартные библиотеки ... :) –

+0

@ user506710 - источник jung 2.0 открыт. Я бы назвал это довольно хорошим началом для того, что делать с чертежными узлами, алгоритмами компоновки и т. Д. – Carl

ответ

2

Вам нужно что-то держать узлы:

 

import java.awt.Color; 
import java.awt.Graphics; 
import java.util.ArrayList; 
import java.util.List; 
import javax.swing.JPanel; 

/** 
* Displays the nodes and connections in the graph 
* @author dvargo 
*/ 
public class DisplayPanel extends JPanel 
{ 
    /** 
    * Holds the nodes in the graph 
    */ 
    List < Node > theNodes = new ArrayList(); 

    public DisplayPanel() 
    { 
     setBackground(Color.white); 
     repaint(); 
     setLayout(null); 

     //will redraw and new lines in the nodes automatically for you 
     new Thread(new Runnable() 
     { 
      public void run() 
      { 
       while (true) 
       { 
        drawConnections(); 
        try 
        { 
         Thread.sleep(100); 
        } 
        catch (Exception e) 
        { 

        } 
       } 
      } 
     }).start(); 
    } 

    /** 
    * Adds a node to the graph 
    * @param newNode The node to add 
    * @param xPosition The x Position in the graph to add it 
    * @param yPosition The y Position in the graph to add it 
    */ 
    public void add(Node newNode, int xPosition, int yPosition) 
    { 
     add(newNode); 
     newNode.setLocation(xPosition, yPosition); 
     theNodes.add(newNode); 
    } 

    /** 
    * Draw the connecting lines between nodes 
    */ 
    public void drawConnections() 
    { 
     Graphics g = getGraphics(); 
     for (Node currNode : theNodes) 
     { 
      for (Node currConnectedNode : currNode.getConnections()) 
      { 
       g.drawLine(currNode.getLocation().x, 
          currNode.getLocation().y, 
          currConnectedNode.getLocation().x, 
          currConnectedNode.getLocation().y); 
      } 
     } 
    } 
} 
 

Далее фактический узел.

 

import java.awt.Color; 
import java.awt.GridBagLayout; 
import java.awt.GridLayout; 
import java.awt.Point; 
import java.awt.event.MouseEvent; 
import java.awt.event.MouseMotionAdapter; 
import java.util.ArrayList; 
import java.util.List; 
import javax.swing.JLabel; 
import javax.swing.JPanel; 

/** 
* Represents a node in the graph 
* @author dvargo 
*/ 
public class Node extends JPanel 
{ 
    /** 
    * Holds all the nodes this node is connected too 
    */ 
    List < Node > connections; 

    /** 
    * Displays the name of this node 
    */ 
    JLabel nameLabel; 

    /** 
    * Reference to the panel that is displaying these nodes 
    */ 
    DisplayPanel displayPanel; 

    /** 
    * Default constructor 
    * @param nodeName The name of this node 
    */ 
    public Node(final DisplayPanel displayPanel, String nodeName) 
    { 
     setBackground(Color.red); 
     this.displayPanel = displayPanel; 
     nameLabel = new JLabel(nodeName); 
     nameLabel.setVisible(true); 
     add(nameLabel); 
     connections = new ArrayList(); 

     //makes the nodes draggable 
     addMouseMotionListener(new MouseMotionAdapter() 
     { 
      public void mouseDragged(MouseEvent e) 
      { 
       setLocation(e.getX() + getLocation().x, 
         e.getY() + getLocation().y); 
       displayPanel.repaint(); 
      } 
     }); 

     setSize(50,50); 
     repaint(); 
    } 

    /** 
    * Change the name of the node 
    * @param newName The new name of the node 
    */ 
    public void setName(String newName) 
    { 
     nameLabel.setText(newName); 
    } 

    /** 
    * Get all the nodes this node is connected to 
    * @return List of nodes this node is connected too 
    */ 
    public List < Node > getConnections() 
    { 
     return connections; 
    } 

    /** 
    * Sets a connection between this node and another node 
    * @param newConnection The node to connect this node too 
    */ 
    public void addConnection(Node newConnection) 
    { 
     connections.add(newConnection); 
     //make sure the other node knows about this connection 
     if(newConnection.getConnections().contains(this) == false) 
     { 
      newConnection.addConnection(this); 
     } 
    } 

    /** 
    * Removes a connection with another node 
    * @param nodeToRemoveConnectionWith The nodes whose connection you could like 
    * to break 
    */ 
    public void removeConnection(Node nodeToRemoveConnectionWith) 
    { 
     connections.remove(nodeToRemoveConnectionWith); 
    } 

} 
 

Это запускает программу

 

import java.awt.GridLayout; 
import javax.swing.JFrame; 

/** 
* Runs the test program 
* @author dvargo 
*/ 
public class Main 
{ 
    public static void main(String [] args) 
    { 
     //build GUI 
     JFrame mainWindow = new JFrame(); 
     mainWindow.setSize(800,800); 
     mainWindow.setLayout(new GridLayout()); 

     DisplayPanel graphPanel = new DisplayPanel(); 
     mainWindow.add(graphPanel); 

     mainWindow.setVisible(true); 
     graphPanel.setVisible(true); 

     //create some nodes 
     Node a = new Node(graphPanel, "A"); 
     Node b = new Node(graphPanel, "B"); 
     Node c = new Node(graphPanel, "C"); 
     Node d = new Node(graphPanel, "D"); 
     Node e = new Node(graphPanel, "E"); 
     Node f = new Node(graphPanel, "F"); 

     a.setVisible(true); 
     b.setVisible(true); 
     c.setVisible(true); 
     d.setVisible(true); 
     e.setVisible(true); 
     f.setVisible(true); 

     //add them to their locations 
     graphPanel.add(a,0,0); 
     graphPanel.add(b,75,100); 
     graphPanel.add(c,400,300); 
     graphPanel.add(d,600,600); 
     graphPanel.add(e,45,600); 
     graphPanel.add(f,700,300); 

     //set the connections 
     a.addConnection(b); 
     a.addConnection(f); 
     b.addConnection(d); 
     b.addConnection(c); 
     b.addConnection(e); 
     c.addConnection(f); 
     e.addConnection(d); 

    } 

} 
 
+0

Обновлено. Узлы перетаскиваются, поэтому вы можете перемещать их. Как я уже сказал, это всего лишь грубая версия того, что вы можете сделать, но должна быть в состоянии заставить вас начать по крайней мере. – user489041

+0

Если у вас есть какие-либо вопросы по этому вопросу, не стесняйтесь спрашивать. – user489041

+0

желание могло добавить больше голосов :) ... большое спасибо .... –

0

Вы хотели бы посмотреть на GraphPanel, что «особенности непостоянны, изменяемого размера, цветные узлы, соединенные ребрами.»

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