我正在使用JList,并且尝试使用JTextAreas(实现ListCellRenderer)作为单元格。它不起作用。单元格仅显示ListCellRenderer.toString()而不是实际的JTextArea。有人可以帮忙吗?谢谢。


  DefaultListModel listModel = new DefaultListModel();
  JList list = new JList(listModel);
  add(list);

class ButtonListener implements ActionListener() {
  public void actionPerformed(ActionEvent e){
    listModel.clear();
    for (String s : stringArray) {
      listModel.addElement(new Listm(s));
    }
  }
}

class Listm extends JTextArea implements ListCellRenderer {
  protected Listm(String text) {
   setText(text); //Outputting the text element displays the desired String
  }

  public Component getListCellRendererComponent(JList list, Object object, int number, boolean bool, boolean bool2) {
    setPreferredSize(new Dimension(x, y));
    return this;
    }
  }
}

最佳答案

您应该只发布可编译的代码,并且您的代码有些混乱。您不应该将文本传递到渲染器的构造函数中,因为该构造函数将用于渲染列表中所有项目的单个渲染器(除非您希望所有人都使用相同的代码)。您不应忽略传递到getListCellRendererComponent方法中的Object参数,因为这是渲染器项目显示的数据。例如:

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

public class MyGui extends JPanel {
   public static final String[] DATA = {"One\n1", "Two\n2", "Three\n3"};
   private DefaultListModel listModel = new DefaultListModel();
   private JList list = new JList(listModel);

   public MyGui() {
      list.setCellRenderer(new Listm(3, 30));
      add(new JScrollPane(list));
      for (String datum : DATA) {
         listModel.addElement(datum);
      }
   }

   private class Listm extends JTextArea implements ListCellRenderer {
      protected Listm(int rows, int cols) {
         super(rows, cols);
         setBorder(BorderFactory.createLineBorder(Color.blue));
      }

      public Component getListCellRendererComponent(JList list, Object value,
               int index, boolean isSelected, boolean cellHasFocus) {
         setText(value.toString());
         if (cellHasFocus) {
            setBackground(FOCUSED_COLOR);
         } else if (isSelected) {
            setBackground(SELECTED_COLOR);
         } else {
            setBackground(null);
         }
         return this;
      }
   }

   private static void createAndShowUI() {
      JFrame frame = new JFrame("MyGui");
      frame.getContentPane().add(new MyGui());
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      java.awt.EventQueue.invokeLater(new Runnable() {
         public void run() {
            createAndShowUI();
         }
      });
   }
}

10-05 21:19