I'm using a JTree to display data on my GUI. Sometimes this data is a string, which is UTF-8 formatted. These strings may contain foreign characters or emojis. My problem is that the strings are display wrong.
Example:
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeNode;
public class Demo {
public static void main(String[] args) {
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
DefaultMutableTreeNode leaf = new DefaultMutableTreeNode("Leaf: 😁");
root.add(leaf);
JTree tree = new JTree(root);
JFrame frame = new JFrame("Demo");
frame.add(new JScrollPane(tree));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
Output:
- Root
|-- []eaf: []
Is it possible to display those strings correctly using a JTree?
For future readers:
Maybe you want to check this, too. Click
tree2.setFont(new Font("DejaVu Sans", 0, 16));
, your code works fine.
JDK1.8.0_66
on Windows 10 x64.import java.awt.*;
import javax.swing.*;
import javax.swing.tree.*;
public class Demo2 {
public JComponent makeUI() {
//String s = "😁";
String s = "\uD83D\uDE01"; //\u1F601
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
DefaultMutableTreeNode leaf = new DefaultMutableTreeNode("Leaf: " + s);
root.add(leaf);
JTree tree1 = new JTree(root);
tree1.setFont(new Font("Lucida Sans", 0, 16));
JTree tree2 = new JTree(root);
tree2.setFont(new Font("DejaVu Sans", 0, 16));
JPanel p = new JPanel(new GridLayout(2, 1));
p.add(new JScrollPane(tree1));
p.add(new JScrollPane(tree2));
return p;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(new Demo2().makeUI());
f.setSize(320, 240);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}