0

正如标题所说,我正在创建一个带有自定义渲染器的 JList。

渲染器只需添加一个 JPanel 并将 JLabel 放入其中。

我正在 JLabel 上尝试“我的文本”技巧,但它仍然拒绝自动换行。

我错过了什么?

更新:我不想硬编码任何尺寸。文本应根据窗口的大小换行(用户当然可以随时调整大小)。

主“ListTest2”类:

import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.JList;

public class ListTest2 extends JFrame {

public static void main(String[] args) {
    new ListTest2();
}

public ListTest2() {

    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setTitle("JList Renderer Example");
    this.setSize(700, 500);
    this.setLocationRelativeTo(null);

    DefaultListModel<String> listModel = new DefaultListModel<>();
    listModel.addElement("USA");

    JList<String> countryList = new JList<>(listModel);
    countryList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    countryList.setCellRenderer(new CountryRenderer());        

    add(new JScrollPane(countryList));

    this.setVisible(true);
}

}

渲染器类:

import java.awt.Color;
import java.awt.Component;

import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JList;
import javax.swing.ListCellRenderer;
import javax.swing.border.LineBorder;

public class CountryRenderer extends JPanel implements ListCellRenderer<String> {

public CountryRenderer() {

    setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
    setBorder(new LineBorder(Color.BLACK, 2));

    JLabel testLabel = new JLabel("<html>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</html>");
    add(testLabel);

}

public Component getListCellRendererComponent(JList<? extends String> list, String value, int index, boolean isSelected, boolean cellHasFocus) {
    return this;
}

}
4

0 回答 0