1

ArrayList からデータを取得する JList の簡単な例がありますが、リスト内の各文字列の横に画像を表示したいと考えています。アイコンとオブジェクトを並べて表示するカスタム セル レンダラー (IconListRenderer) を作成しました。

これが実行中のサンプルです。

//Test class showing the list in a frame
import java.awt.Color;
import java.awt.Dimension;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import javax.swing.*;
import javax.swing.border.LineBorder;


public class Test extends JFrame{

     public static void main(String[] args) {


    final JFileChooser chooser = new JFileChooser();
    JButton button = new JButton();
    button.setText("Upload");
    JFrame frame = new JFrame("My Frame");
    JList list = new JList();
    Map<Object, ImageIcon> icons = new HashMap<Object, ImageIcon>();
    list.setBorder(new LineBorder(Color.BLACK));

    ImageIcon icon = new ImageIcon("/Images/400px-Greek_uc_sigma.png");

    ArrayList<String> arrayList = new ArrayList<String>();

    icons.put("Name", icon);

    //populate the arrayList for testing
    arrayList.add("Smith");
    arrayList.add("John");
    arrayList.add("Bob");
    arrayList.add("Kim");

    frame.setSize(new Dimension(400, 400));
    //set the list data
    list.setListData(arrayList.toArray());
    final JFrame imageFrame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


    list.setCellRenderer(new IconListRenderer(icons));
    frame.add(list); 
    frame.setVisible(true);
    frame.repaint();
}



}

//IconListRenderer クラス

import java.awt.Component;
import java.util.Map;
import javax.swing.DefaultListCellRenderer;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JList;


 public class IconListRenderer
                           extends DefaultListCellRenderer {

private Map<Object, ImageIcon> icons = null;

public IconListRenderer(Map<Object, ImageIcon> icons) {
    this.icons = icons;
}

@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;
}
  }

リストは現在表示されていますが、画像はありませんか?

4

1 に答える 1

2

それは本当に驚くべきことではありません:

  • JList 項目の値をキーとして使用して、アイコン マップからアイコンを取得します。
  • アイコンマップには、「名前」という単一のキーが含まれています
  • JList には「Smith」、「John」、「Bob」、および「Kim」が含まれていますが、「Name」は含まれていません
于 2011-08-06T22:30:42.130 に答える