本文介绍了JList项目中的自动换行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我有一个 JList ,其项目名称非常长,导致水平滚动条显示在滚动窗格中。

I have a JList with very long item names that cause the horizontal scroll-bar to appear in scroll-pane.

无论如何,我可以自动换行,以便整个项目名称出现在2行中,但只需点击一下即可选择? IE它仍应表现作为单个项目,但显示分为两行。

Is there anyway that I can word wrap so that the whole whole item name appears in 2 rows yet can be selected in one click? I.E it should still behave as a single item but be displayed in two rows.

以下是看到下面的例子后我做的事情

Here is what I did after seeing the example below

我在我的项目MyCellRenderer中添加了一个新类,然后我添加了 MyList.setCellRenderer(new MyCellRenderer(80)); 在我的列表的帖子创建代码中。还有什么我需要做的吗?

I added a new class to my project MyCellRenderer and then I went added MyList.setCellRenderer(new MyCellRenderer(80)); in the post creation code of my List. Is there anything else I need to do?

推荐答案

是的,使用安德鲁的代码,我想出了类似的东西:

Yep, using Andrew's code, I came up with something like this:

import java.awt.Component;
import javax.swing.*;

public class JListLimitWidth {
   public static void main(String[] args) {
      String[] names = { "John Smith", "engelbert humperdinck",
            "john jacob jingleheimer schmidt" };
      MyCellRenderer cellRenderer = new MyCellRenderer(80);
      JList list = new JList(names);
      list.setCellRenderer(cellRenderer);
      JScrollPane sPane = new JScrollPane(list);
      JPanel panel = new JPanel();
      panel.add(sPane);
      JOptionPane.showMessageDialog(null, panel);

   }
}

class MyCellRenderer extends DefaultListCellRenderer {
   public static final String HTML_1 = "<html><body style='width: ";
   public static final String HTML_2 = "px'>";
   public static final String HTML_3 = "</html>";
   private int width;

   public MyCellRenderer(int width) {
      this.width = width;
   }

   @Override
   public Component getListCellRendererComponent(JList list, Object value,
         int index, boolean isSelected, boolean cellHasFocus) {
      String text = HTML_1 + String.valueOf(width) + HTML_2 + value.toString()
            + HTML_3;
      return super.getListCellRendererComponent(list, text, index, isSelected,
            cellHasFocus);
   }

}

这篇关于JList项目中的自动换行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-07 01:51