Search code examples
javauser-interfacejgraph

From a string array to a diagram of blocks


I have made a program which takes the results of some SPARQL queries through Jena and saves them in a 2-dimensional string (i.e., 2-dimensional array of Strings). I want to take the values of the first column only and design a diagram of blocks where every block contains every value of the first column and links them successively with each other.

From what I have read, JGraph seems to be pretty helpful for this, but I downloaded it and tried to do it but I failed.

How could I do this with JGraph, or are there other ways?

something like this


Solution

  • Here's a method I put together that will draw a rectangle, fill it with a color, and put a String at the center of the rectangle.

    /**
     * <p>This method will draw a rectangle and place the text in the center
     * of the rectangle.</p>
     * @param g - Graphics instance from a JPanel paintComponent method
     * @param r - Rectangle (origin and dimension) of the rectangle.
     * @param c - Fill color of the rectangle.
     * @param s - String to place at the center of the rectangle.
     */
    public void drawBox(Graphics g, Rectangle r, Color c, String s) {
        g.setColor(c);
        g.fillRect(r.x, r.y, r.width, r.height);
    
        Graphics2D g2d = (Graphics2D) g;
        FontRenderContext frc = g2d.getFontRenderContext();
        TextLayout layout = new TextLayout(s, g.getFont(), frc);
        Rectangle2D bounds = layout.getBounds();
    
        int width = (int) Math.round(bounds.getWidth());
        int height = (int) Math.round(bounds.getHeight());
        int x = r.x + (r.width - width) / 2;
        int y = r.y + height + (r.height - height) / 2;
    
        g.setColor(Color.BLACK);
        layout.draw(g2d, (float) x, (float) y);
    }
    

    You'll have to figure out where you want the rectangles and how to connect them with skinny rectangles.