如何用图片替换文字中的单词?

时间:2016-01-05 18:43:01

标签: java swing

现在我将DefaultListModel与所需的字符串列表一起使用,并通过JList在JScrollPane中显示它。

我想要的是在这个句子中找到一个特定的单词并放置一个imageIcon而不是我将在所述JScrollPane中显示的这个单词。

例如,我想用猫图标替换单词“cat”,字符串将是:

"the little cat is good"
"there is no tomorrow" 
"cat is what I need"

我想要的输出是带有项目的JScrollPane:

"the little *cat icon* is good"
"there is no tomorrow" 
"*cat icon* is what I need"

我发现建议创建自定义ListCellRenderer来替换DefaultListModel。在所有示例中,imageIcon作为图标添加到标签中,遗憾的是,这只在文本的开头添加了一个图标,这不是我想要的。

以下是this site中的一个示例中的相关部分:

@Override
public Component getListCellRendererComponent(
    JList list, Object value, int index, 
    boolean isSelected, boolean cellHasFocus) {

    // Get the renderer component from parent class

    JLabel label = 
        (JLabel) super.getListCellRendererComponent(list, 
            value, index, isSelected, cellHasFocus);

    // Get icon to use for the list item value

    Icon icon = icons.get(value);

    // Set icon to display for value

    label.setIcon(icon);
    return label;
}

那么,如何在JList中的文本中添加图标?

任何建议将不胜感激。谢谢

2 个答案:

答案 0 :(得分:3)

我会使用JTextPaneinsertIcon(...)方法。

有关工作示例,请参阅Text Component Features上的Swing教程中的部分。

该示例仅显示如何插入Icon。您可以自行解析要替换的字符串的文本。找到要替换的String后,可以使用以下代码:

textPane.setSelectionStart(...);
textPane.setSelectionEnd(...);
textPane.replaceSelection(...);
textPane.insertIcon(...);

答案 1 :(得分:3)

您可以使用JLabel html 功能,将cat切换为<img src='cat.png'/>

实施例

public class JListTest extends JPanel{  
  private static final long serialVersionUID = 1L;

  public JListTest(){
    this.setLayout(new BorderLayout());
    JScrollPane scrollPane = new JScrollPane();
    String[] data = {"the little cat is good", "there is no tomorrow" , "cat is what I need"};
    switchToHtml(data);
    replaceWithImage(data,"cat","cat.png");
    JList<String> list = new JList<String>(data);
    scrollPane.getViewport().add(list);
    this.add(scrollPane,BorderLayout.CENTER);       
  }

  private void replaceWithImage(String[] data, String replace, String image) {
    for (int i = 0; i < data.length; i++) {
        String text = data[i];
        if (text.contains(replace)){
            text = text.replaceAll(replace, "<img src=\"" + JListTest.class.getResource(image) + "\">");
            data[i]=text;
        }           
    }
  }

 private void switchToHtml(String[] data) {
    for (int i = 0; i < data.length; i++) {
        data[i]="<html><body>" + data[i] + "</body></html>";
    }
 }

 public static void main(String[] args) {
    JFrame frame = new JFrame("Test");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(new BorderLayout());
    frame.getContentPane().add(new JListTest(),BorderLayout.CENTER);
    frame.pack();
    frame.setVisible(true);
 }
}

要进行测试,只需在与cat.png相同的包中添加class

结果(有一个不错的小猫)

Result