格式化Jlabel-JTextBox [英] Format Jlabel - JTextBox

查看:95
本文介绍了格式化Jlabel-JTextBox的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一台简单的二叉树打印机:

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;
}

如果我在eclipse控制台中运行它,我将得到:

If I run it in the eclipse console i get:

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

我的问题是我试图在UI上显示它,所以当我将它放在JLabel上不起作用时,我曾尝试使用< html>,而不是\ n->< br>但它也不起作用,最好的方法是什么?我已经尝试过使用JFormattedTextField,但它似乎不起作用.

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.

谢谢.

推荐答案

有多种可能的方法可以实现此目的.您可以创建一个可以绘制结构的自定义组件.您可以使用JTree,也可以使用JTextArea之类的东西.

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);

这篇关于格式化Jlabel-JTextBox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆