gpt4 book ai didi

java - 重新调整 JList 元素内部的文本

转载 作者:行者123 更新时间:2023-12-02 11:03:41 25 4
gpt4 key购买 nike

我有一个JList,该列表填充了文件的元素,我希望将元素内的文本调整为列表的大小,增加单元格的高度并给出换行符。

enter image description here

我该怎么做?

最佳答案

I want the text within the elements to be adjusted to the size of the list

列表单元格渲染器(通常是 JLabel)支持 HTML 格式,因此我们可以使用样式来设置正文宽度。单元格的高度将相应调整。中间列表使用宽度限制为 100 像素的渲染器。

enter image description here

这是基于前 1000 个 Unicode 字符的属性的三个列表。每个列表都具有所需的宽度,以便在列表模型中显示最宽的字符串(但是它的格式是为了渲染而设置的)。

这是 MCVE:

import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.util.Vector;

public class UnicodeNameList {

private JComponent ui = null;

UnicodeNameList() {
initUI();
}

public final void initUI() {
if (ui!=null) return;

ui = new JPanel(new BorderLayout(4,4));
ui.setBorder(new EmptyBorder(4,4,4,4));
Vector<String> unicodeNames = new Vector<>();
Vector<String> unicodeDir = new Vector<>();
Vector<String> unicodeChar = new Vector<>();
for (int ii=0; ii<1000; ii++) {
unicodeChar.add(new String(Character.toChars(ii)));
unicodeNames.add(Character.getName(ii));
unicodeDir.add("" + Character.getDirectionality(ii));
}
ui.add(new JScrollPane(new JList(unicodeChar)), BorderLayout.LINE_START);
JList list = new JList(unicodeNames);
LongListCellRenderer llcr = new LongListCellRenderer();
list.setCellRenderer(llcr);
ui.add(new JScrollPane(list));
ui.add(new JScrollPane(new JList(unicodeDir)), BorderLayout.LINE_END);
}

public JComponent getUI() {
return ui;
}

public static void main(String[] args) {
Runnable r = () -> {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
UnicodeNameList o = new UnicodeNameList();

JFrame f = new JFrame(o.getClass().getSimpleName());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);

f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());

f.setVisible(true);
};
SwingUtilities.invokeLater(r);
}
}

class LongListCellRenderer extends DefaultListCellRenderer {

@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
String pre = "<html><body style='width: 100px;'>";
JLabel l = (JLabel)super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
String s = value==null ? "Null" : value.toString();
l.setText(pre + s);
return l;
}
}

关于java - 重新调整 JList 元素内部的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51145148/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com