如何在JList自定义渲染器中创建JLabel word.wrap?

时间:2014-03-13 13:04:35

标签: java swing jlist word-wrap listcellrenderer

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

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

我在JLabel上尝试“MY TEXT”技巧,但它仍然拒绝自动换行。

我错过了什么?

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

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

}

0 个答案:

没有答案