How can I generate a tag cloud in Java, with OpenCloud?

coder picture coder · Jul 14, 2012 · Viewed 13.6k times · Source

I was looking for a library to create tag clouds in a Java application, and I found OpenCloud.

I don't want to have to use a web server, which OpenCloud will require to get the output in, won't it? Is there a way to get OpenCloud to work in a Java/Swing panel? I want something for a stand alone application. If this isn't possible, where else can I look for such an API?

Answer

Guillaume Polet picture Guillaume Polet · Jul 14, 2012

Actually OpenCloud does not require a Web server. Simply use Swing rendering instead of HTML/JSP. Here is a small snippet illustrating a very basic Swing tag cloud using OpenCloud library. It can be improved, but it gives you the gist:

import java.util.Random;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

import org.mcavallo.opencloud.Cloud;
import org.mcavallo.opencloud.Tag;

public class TestOpenCloud {

    private static final String[] WORDS = { "art", "australia", "baby", "beach", "birthday", "blue", "bw", "california", "canada", "canon",
            "cat", "chicago", "china", "christmas", "city", "dog", "england", "europe", "family", "festival", "flower", "flowers", "food",
            "france", "friends", "fun", "germany", "holiday", "india", "italy", "japan", "london", "me", "mexico", "music", "nature",
            "new", "newyork", "night", "nikon", "nyc", "paris", "park", "party", "people", "portrait", "sanfrancisco", "sky", "snow",
            "spain", "summer", "sunset", "taiwan", "tokyo", "travel", "trip", "uk", "usa", "vacation", "water", "wedding" };

    protected void initUI() {
        JFrame frame = new JFrame(TestOpenCloud.class.getSimpleName());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel panel = new JPanel();
        Cloud cloud = new Cloud();
        Random random = new Random();
        for (String s : WORDS) {
            for (int i = random.nextInt(50); i > 0; i--) {
                cloud.addTag(s);
            }
        }
        for (Tag tag : cloud.tags()) {
            final JLabel label = new JLabel(tag.getName());
            label.setOpaque(false);
            label.setFont(label.getFont().deriveFont((float) tag.getWeight() * 10));
            panel.add(label);
        }
        frame.add(panel);
        frame.setSize(800, 600);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new TestOpenCloud().initUI();
            }
        });
    }

}

This code is based on the Example 1 of the OpenCloud library

Here is an output of what I got:

Swing tag cloud demo image