Format Jlabel - JTextBox

佐手、 提交于 2019-12-25 07:45:11

问题


I have a simple binary tree printer:

public String displayTree(){
    if(root != null){
        return this.toString(new StringBuilder(), true, new StringBuilder(), root).toString();
    }else{
        return "Empty tree";
    }
}   

private StringBuilder toString(StringBuilder prefix, boolean isLeft, StringBuilder sb, BinaryNode<T> node) {
    if(node.getRight() !=null) {
        toString(new StringBuilder().append(prefix).append(esIzquierdo ? "│   " : "    "), false, sb, node.getRight());
    }
    sb.append(prefix).append(isLeft? "└── " : "┌── ").append(node.getItem().toString()).append("\n");
    if(node.getLeft() != null) {
        toString(new StringBuilder().append(prefix).append(esIzquierdo ? "    " : "│   "), true, sb, node.getLeft());
    }
    return sb;
}

If I run it in the eclipse console i get:

     │           ┌── K
     │       ┌── F
     │       │   │   ┌── L
     │       │   └── J
     │   ┌── C
     │   │   │   ┌── I
     │   │   └── E
     └── A
         │       ┌── H
         │   ┌── D
         │   │   └── G
         └── B

My problem is that i'm trying to display it on a UI, so when I put it on the JLabel it doesn't work, I have tried formatting it with < html > and instead of \n -> < br > but it doesn't work either, what's the best way of doing that? I have tried with a JFormattedTextField but it doesn't seem to work.

Thank you.


回答1:


There are a number of possible ways you might achieve this. You could create a custom component which can paint the structure; you could use a JTree or you could use something like a JTextArea.

The trick is making sure you're using a fixed width font

String tree = "│           ┌── K\n"
        + "│       ┌── F\n"
        + "│       │   │   ┌── L\n"
        + "│       │   └── J\n"
        + "│   ┌── C\n"
        + "│   │   │   ┌── I\n"
        + "│   │   └── E\n"
        + "└── A\n"
        + "    │       ┌── H\n"
        + "    │   ┌── D\n"
        + "    │   │   └── G\n"
        + "    └── B";
JTextArea ta = new JTextArea(15, 25);
ta.setText(tree);
ta.setFont(new Font("Monospaced", Font.PLAIN, 13));
JFrame frame = new JFrame();
frame.add(new JScrollPane(ta));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);


来源:https://stackoverflow.com/questions/43727494/format-jlabel-jtextbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!