Java Swing How to - Create Listview from JLabel








Question

We would like to know how to create Listview from JLabel.

Answer

import java.awt.Dimension;
import java.awt.Font;
import java.awt.GraphicsEnvironment;
// w ww. j a  va2 s  .c o m
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;

public class Main {
  public static void main(String[] args) {
    final StringBuilder sb = new StringBuilder();
    sb.append("<html>");
    sb.append("<body><ol>");
    Font[] fonts = GraphicsEnvironment.getLocalGraphicsEnvironment()
        .getAllFonts();
    for (Font font : fonts) {
      String name = font.getName();
      sb.append("<li style='font-family: " + name + "; font-size: 20px;'>");
      sb.append(name);
    }

    JScrollPane sp = new JScrollPane(new JLabel(sb.toString()));
    Dimension d = sp.getPreferredSize();
    sp.setPreferredSize(new Dimension(d.width, 150));
    JOptionPane.showMessageDialog(null, sp);
  }
}