Java Swing How to - Make search result all in one box with HTML








Question

We would like to know how to make search result all in one box with HTML.

Answer

//from  w  w w. ja  va  2 s.com
import java.awt.Color;
import java.awt.GridLayout;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.MatteBorder;

public class Main {

  public static void main(String[] args) {
    List<Phone> phones = new ArrayList<>();
    phones.add(new Phone("Galaxy", 12345));
    phones.add(new Phone("iPhone", 12345));

    JPanel panel = new JPanel(new GridLayout(0, 1));
    for (Phone phone : phones) {
      String html = "<html><body style='width:100px'>Phone: " + phone.getName()
          + "<br/>Model: " + phone.getModel() + "</body></html>";
      JLabel label = new JLabel(html);
      label.setBorder(new MatteBorder(0, 0, 1, 0, Color.BLACK));
      panel.add(label);

    }
    JOptionPane.showMessageDialog(null, panel, "Phone List",
        JOptionPane.PLAIN_MESSAGE);
  }

}

class Phone {
  private String name;
  private int model;

  public Phone(String name, int model) {
    this.name = name;
    this.model = model;
  }

  public String getName() {
    return name;
  }

  public int getModel() {
    return model;
  }
}