-1

编辑:这是@HovercraftFullOfEels 回答后更新的代码:

注意:我没有使用 HashMap,因为我想做几个动作,比如改变颜色和使字体变为粗体或斜体,而答案中提供的 HashMap 仅用于将特定颜色设置为特定枚举类型。

所以,这里是代码:

package src;

import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.Font;

import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;

import src.MainWindow.LogType;

public class MainWindow {

    public enum LogType {
        ERROR("Error"), COMMENT("Comment"), READ_INFO("Read_Info"), ACTION(
                "Action"), PARAM_ERROR("Param_Error");
        String text;

        private LogType(String s) {
            this.text = s;
        }

        public void setText(String s) {
            this.text = s;
        }

        public String getText() {
            return text;
        }
    };

    private JFrame frmNavdng;
    private static DefaultListModel<LogType> logListModel = new DefaultListModel<>();
    private static JList<LogType> log_List = new JList<>(logListModel);

    public MainWindow() {
        initialize();
    }

    public static void add_Log_Line(LogType type, String s) {
        // add action to the log list
        type.setText(s);
        logListModel.addElement(type);
        log_List.ensureIndexIsVisible(log_List.getLastVisibleIndex());
    }

    private void initialize() {
        /** Frame Initialisation */
        frmNavdng = new JFrame();
        frmNavdng.setFont(new Font("Tahoma", Font.PLAIN, 12));
        frmNavdng.setTitle("list_window");
        frmNavdng.setResizable(false);
        frmNavdng.setBounds(100, 100, 640, 400);
        frmNavdng.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frmNavdng.getContentPane().setLayout(null);

        JScrollPane scrollPane = new JScrollPane();
        scrollPane.setBounds(0, 0, frmNavdng.getWidth(), frmNavdng.getHeight());
        frmNavdng.getContentPane().add(scrollPane);
        scrollPane.setViewportView(log_List);
        log_List.setToolTipText("history of the last actions");
        log_List.setVisibleRowCount(10);
        log_List.setValueIsAdjusting(true);
        log_List.setFont(new Font("Tahoma", Font.PLAIN, 10));
        log_List.setCellRenderer(new MyCellRenderer());
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    MainWindow window = new MainWindow();
                    window.frmNavdng.setVisible(true);
                    for (int i = 0; i <= 5; i++) {
                        add_Log_Line(LogType.ACTION, ("loop " + i));
                    }
                } catch (Exception e) {
                    e.toString();
                }
            }
        });
    }

}

class MyCellRenderer extends DefaultListCellRenderer {

    private static final long serialVersionUID = 1L;

    public MyCellRenderer() {
        setOpaque(true);
    }

    @Override
    public Component getListCellRendererComponent(JList<?> list, Object value,
            int index, boolean isSelected, boolean cellHasFocus) {
        LogType lt = (LogType) value;   

        value = lt.getText();

        Color background = Color.white;
        Color foreground = Color.black;
        Font font = list.getFont();

        if (lt == LogType.ACTION) {
            foreground = Color.blue;
        }

        if (lt == LogType.COMMENT) {
            foreground = Color.darkGray;
        }

        if (lt == LogType.ERROR) {
            foreground = Color.red;
            font = new Font(list.getFont().getFontName(), Font.BOLD, list
                .getFont().getSize());
        }

        if (lt == LogType.READ_INFO) {
            foreground = Color.magenta;
            font = new Font(list.getFont().getFontName(), Font.ITALIC, list.getFont().getSize());
        }

        if (lt == LogType.PARAM_ERROR) {
            foreground = Color.orange;
            font = new Font(list.getFont().getFontName(), Font.BOLD, list
                .getFont().getSize());
        }

        if (isSelected)
            background = Color.lightGray;

        Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);

        c.setForeground(foreground);
        c.setBackground(background);
        c.setFont(font);

        return c;
    }
}

编辑2:这是我得到的和我想要得到的说明:

如果我运行@HovercraftFullofEels 给出的代码,稍作修改以更改文本:

for(int i = 0; i<= 10; i++)
{
    LogType logType = LogType.values()[i];
    //just added this line
    logType.setText("Type : " + logType.toString() + " - Loop : " + i);
    logListModel.addElement(logType);
}

我得到了这个结果: 我通过运行代码得到什么 每种类型的日志都会得到每个日志的最后一个文本......如果他们能得到我一开始给他们的文本,那就太好了,这样我就可以显示像“打开失败”这样的文本文件”带有ERROR类型和样式,“这个文件中给定的参数错误,将被忽略”带有READ_INFO样式和类型,“结果写入文件result.txt”作为ACTION,例如.

使用给出的代码,我不知道如何以及在何处设置此文本并将其设置为“静态”(这意味着它不会在此处更改)。

- - - - - - - - - 老问题 - - - - - - - - -

我使用JList作为日志查看器,我想添加一些不同颜色的行。例如,我有一个COMMENTACTIONERRORenum类型。COMMENT为深灰色,ACTION为蓝色,ERROR为红色。

我试图进行自定义ListCellRendered,但我无法弄清楚如何根据enum.

这是我的代码:

public class MainWindow {
/* all the other declarations... */
private static JList<String> log_List;

/* configuration of the list somewhere in the code */
log_List = new JList<String>(new DefaultListModel<String>());
scrollPane.setViewportView(log_List);
log_List.setToolTipText("history of the last actions");
log_List.setVisibleRowCount(10);
log_List.setValueIsAdjusting(true);
log_List.setCellRenderer(new MyCellRenderer());

public enum LOG_TYPE {
    ERROR, COMMENT, READ_INFO, ACTION
};

// add action to the log list
public static void add_Log_Line(LOG_TYPE type, String s) {
//what I did before, but not working... 
/* if (type == LOG_TYPE.ERROR)  log_List.setForeground(Color.red);
    if (type == LOG_TYPE.ACTION) log_List.setForeground(Color.blue);
    if (type == LOG_TYPE.COMMENT) log_List.setForeground(Color.darkGray);
    if (type == LOG_TYPE.READ_INFO)log_List.setForeground(Color.magenta); */

    ((DefaultListModel<String>) log_List.getModel()).addElement(s);
    //makes the last raw visible after adding a line
    log_List.ensureIndexIsVisible(log_List.getLastVisibleIndex());
}

/* somewhere else in the code */
//add the path of a file chosen in a JFileChooser (fc)
add_Log_Line(LOG_TYPE.ACTION, "OPEN - " + fc.getSelectedFile().getAbsolutePath());


/* My custom cell renderer */
class MyCellRenderer extends JLabel implements ListCellRenderer<Object> {
public MyCellRenderer() {
    setOpaque(true);
}

public Component getListCellRendererComponent(JList<?> list, Object value,
        int index, boolean isSelected, boolean cellHasFocus) {

    setText(value.toString());

    Color background = Color.white;
    Color foreground = Color.black;

    if (value == LOG_TYPE.ACTION)
        foreground = Color.blue;
    if (value == LOG_TYPE.COMMENT)
        foreground = Color.darkGray;
    if (value == LOG_TYPE.ERROR)
        foreground = Color.red;
    if (value == LOG_TYPE.READ_INFO)
        foreground = Color.magenta;

    setForeground(foreground);
    setBackground(background);

    return this;
}

}

我得到的只是白底黑字...

4

2 回答 2

2

我怀疑您是否真的想将日志类型添加到 JList。我添加了一个名为LogEntry并更新了代码的类。看看有没有帮助。

package src;

import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.Font;

import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;

import com.sun.javafx.css.converters.FontConverter.FontStyleConverter;

import src.MainWindow.LogEntry;
import src.MainWindow.LogType;

public class MainWindow {

    public enum LogType {
        // @formatter:off
        ERROR("Error", Color.RED, Font.BOLD),
        COMMENT("Comment", Color.BLUE, Font.ITALIC),
        READ_INFO("Read_Info", Color.BLACK, 0),
        ACTION("Action", Color.YELLOW, 0),
        PARAM_ERROR("Param_Error", Color.RED, Font.ITALIC | Font.BOLD);
        // @formatter:on

        String text;
        Color color;
        int fontStyle;

        private LogType(String s, Color color, int fontStyle) {
            this.text = s;
            this.color = color;
            this.fontStyle = fontStyle;
        }

        public void setText(String s) {
            this.text = s;
        }

        public String getText() {
            return text;
        }

        public int getFontStyle() {
            return fontStyle;
        }

        public Color getColor() {
            return color;
        }
    };

    public static class LogEntry {
        private LogType type;
        private String text;

        public LogEntry(LogType type, String text) {
            this.type = type;
            this.text = text;
        }

        public LogType getType() {
            return type;
        }

        public String getText() {
            return text;
        }
    }

    private JFrame frmNavdng;
    private static DefaultListModel<LogEntry> logListModel = new DefaultListModel<>();
    private static JList<LogEntry> log_List = new JList<>(logListModel);

    public MainWindow() {
        initialize();
    }

    public static void add_Log_Line(LogType type, String s) {
        // add action to the log list
        type.setText(s);
        logListModel.addElement(new LogEntry(type, s));
        log_List.ensureIndexIsVisible(log_List.getLastVisibleIndex());
    }

    private void initialize() {
        /** Frame Initialisation */
        frmNavdng = new JFrame();
        frmNavdng.setFont(new Font("Tahoma", Font.PLAIN, 12));
        frmNavdng.setTitle("list_window");
        frmNavdng.setResizable(false);
        frmNavdng.setBounds(100, 100, 640, 400);
        frmNavdng.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frmNavdng.getContentPane().setLayout(null);

        JScrollPane scrollPane = new JScrollPane();
        scrollPane.setBounds(0, 0, frmNavdng.getWidth(), frmNavdng.getHeight());
        frmNavdng.getContentPane().add(scrollPane);
        scrollPane.setViewportView(log_List);
        log_List.setToolTipText("history of the last actions");
        log_List.setVisibleRowCount(10);
        log_List.setValueIsAdjusting(true);
        log_List.setFont(new Font("Tahoma", Font.PLAIN, 10));
        log_List.setCellRenderer(new MyCellRenderer());
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    MainWindow window = new MainWindow();
                    window.frmNavdng.setVisible(true);
                    LogType[] values = LogType.values();
                    for (LogType logType : values) {
                        add_Log_Line(logType, "This is log type " + logType.getText());
                    }
                } catch (Exception e) {
                    e.toString();
                }
            }
        });
    }

}

class MyCellRenderer extends DefaultListCellRenderer {

    private static final long serialVersionUID = 1L;

    public MyCellRenderer() {
        setOpaque(true);
    }

    @Override public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected,
            boolean cellHasFocus) {
        LogEntry entry = (LogEntry) value;

        value = entry.getText();

        Color background = Color.white;
        Color foreground = entry.getType().getColor();

        Font font = list.getFont();

        font = new Font(list.getFont().getFontName(), entry.getType().getFontStyle(), list.getFont().getSize());

        if (isSelected)
            background = Color.lightGray;

        Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);

        c.setForeground(foreground);
        c.setBackground(background);
        c.setFont(font);

        return c;
    }
}
于 2015-07-27T15:23:34.267 回答
1

根据我们的讨论,在渲染器中设置颜色,并在那里设置文本。在这里,我更改了枚举,以便它返回一个显示字符串,但 HashMap 也可以。我确实使用 HashMap 来存储所需的颜色:

import java.awt.Color;
import java.awt.Component;
import java.util.HashMap;
import java.util.Map;
import javax.swing.*;

@SuppressWarnings("serial")
public class MainWindow extends JPanel {
   private DefaultListModel<LogType> logListModel = new DefaultListModel<>();
   private JList<LogType> logList = new JList<>(logListModel);
   private Map<LogType, Color> logTypeColorMap = new HashMap<>();

   public MainWindow() {
      logList.setPrototypeCellValue(LogType.COMMENT); // longest one

      for (int i = 0; i < 30; i++) {
         int index = (int) (Math.random() * LogType.values().length);
         LogType logType = LogType.values()[index];// get a random LogType
         logListModel.addElement(logType);
      }

      logList.setVisibleRowCount(10);
      logList.setCellRenderer(new MyCellRenderer());

      add(new JScrollPane(logList));
   }

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

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

enum LogType {
   ERROR("Error"), COMMENT("Comment"), READ_INFO("Read Info"), ACTION("Action"); 
   private String text;

   private LogType(String text) {
      this.text = text;
   }

   public String getText() {
      return text;
   }
};

@SuppressWarnings("serial")
class MyCellRenderer extends DefaultListCellRenderer {
   private Map<LogType, Color> logTypeColorMap = new HashMap<>();

   public MyCellRenderer() {
      logTypeColorMap.put(LogType.ACTION, Color.blue);
      logTypeColorMap.put(LogType.COMMENT, Color.darkGray);
      logTypeColorMap.put(LogType.ERROR, Color.red);
      logTypeColorMap.put(LogType.READ_INFO, Color.magenta);
   }

   @Override
   public Component getListCellRendererComponent(JList<?> list, Object value,
         int index, boolean isSelected, boolean cellHasFocus) {
      LogType logType = (LogType) value;
      Color color = logTypeColorMap.get(logType);
      value = logType.getText(); // extract text
      Component c =super.getListCellRendererComponent(list, value, index, isSelected,
            cellHasFocus);
      c.setForeground(color);
      return c;
   }
}

您的代码有问题 - 请参阅评论(使用\\ !!)和更正:

import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.Font;
import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;

//!! import src.MainWindow.LogType;

public class MainWindow {

   private JFrame frmNavdng;
   private static DefaultListModel<LogType> logListModel = new DefaultListModel<>();
   private static JList<LogType> log_List = new JList<>(logListModel);

   public MainWindow() {
      initialize();
   }

   // !! get rid of this method as it is doing you no good whatsoever
   public static void add_Log_Line(LogType type, String s) {
      // type.setText(s);
      logListModel.addElement(type);
      log_List.ensureIndexIsVisible(log_List.getLastVisibleIndex());
   }

   private void initialize() {
      frmNavdng = new JFrame();
      frmNavdng.setFont(new Font("Tahoma", Font.PLAIN, 12));
      frmNavdng.setTitle("list_window");
      frmNavdng.setResizable(false);
      frmNavdng.setBounds(100, 100, 640, 400);
      frmNavdng.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frmNavdng.getContentPane().setLayout(null);

      JScrollPane scrollPane = new JScrollPane();
      scrollPane.setBounds(0, 0, frmNavdng.getWidth(), frmNavdng.getHeight());
      frmNavdng.getContentPane().add(scrollPane);
      scrollPane.setViewportView(log_List);
      log_List.setToolTipText("history of the last actions");
      log_List.setVisibleRowCount(10);
      log_List.setValueIsAdjusting(true);
      log_List.setFont(new Font("Tahoma", Font.PLAIN, 10));
      log_List.setCellRenderer(new MyCellRenderer());
   }

   public static void main(String[] args) {
      EventQueue.invokeLater(new Runnable() {
         public void run() {
            MainWindow window = new MainWindow();
            window.frmNavdng.setVisible(true);
            for (int i = 0; i < LogType.values().length; i++) {
               // !! add_Log_Line(LogType.ACTION, ("loop " + i));
               // !! just add to the list model the actual LogType
               LogType logType = LogType.values()[i];
               logListModel.addElement(logType);
            }
         }
      });
   }

}

class MyCellRenderer extends DefaultListCellRenderer {

   private static final long serialVersionUID = 1L;

   public MyCellRenderer() {
      setOpaque(true);
   }

   @Override
   public Component getListCellRendererComponent(JList<?> list, Object value,
         int index, boolean isSelected, boolean cellHasFocus) {
      LogType lt = (LogType) value;

      value = lt.getText();

      Color background = Color.white;
      Color foreground = Color.black;
      Font font = list.getFont();

      // !! note that you could hard-code the String held by value
      // here in these if blocks
      if (lt == LogType.ACTION) {
         foreground = Color.blue;
      }

      if (lt == LogType.COMMENT) {
         foreground = Color.darkGray;
      }

      if (lt == LogType.ERROR) {
         foreground = Color.red;
         font = new Font(list.getFont().getFontName(), Font.BOLD, list
               .getFont().getSize());
      }

      if (lt == LogType.READ_INFO) {
         foreground = Color.magenta;
         font = new Font(list.getFont().getFontName(), Font.ITALIC, list
               .getFont().getSize());
      }

      if (lt == LogType.PARAM_ERROR) {
         foreground = Color.orange;
         font = new Font(list.getFont().getFontName(), Font.BOLD, list
               .getFont().getSize());
      }

      if (isSelected)
         background = Color.lightGray;

      Component c = super.getListCellRendererComponent(list, value, index,
            isSelected, cellHasFocus);

      c.setForeground(foreground);
      c.setBackground(background);
      c.setFont(font);

      return c;
   }
}

就我自己而言,我仍然喜欢 Maps 压缩代码的方式,使其更易于调试和使用。例如,我会考虑做这样的事情:

import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.util.EnumMap;
import java.util.Map;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class MainWindow2 extends JPanel {
   private static final long serialVersionUID = 1L;
   private static final Font FONT = new Font(Font.DIALOG, Font.PLAIN, 12);
   private static DefaultListModel<LogType> logListModel = new DefaultListModel<>();
   private static JList<LogType> logList = new JList<>(logListModel);

   public MainWindow2() {
      Map<LogType, LogWrapper> wrapperMap = new EnumMap<>(LogType.class);
      wrapperMap.put(LogType.ACTION, new LogWrapper("Action", Font.PLAIN, Color.BLUE));
      wrapperMap.put(LogType.COMMENT, new LogWrapper("Comment", Font.PLAIN, Color.DARK_GRAY));
      wrapperMap.put(LogType.ERROR, new LogWrapper("Error", Font.BOLD, Color.RED));
      wrapperMap.put(LogType.READ_INFO, new LogWrapper("Read Info", Font.ITALIC, Color.MAGENTA));
      wrapperMap.put(LogType.PARAM_ERROR, new LogWrapper("Parameter Error", Font.BOLD, Color.ORANGE));

      for (int i = 0; i < LogType.values().length * 3; i++) {
         int index = i % LogType.values().length;
         logListModel.addElement(LogType.values()[index]);
      }

      logList.setToolTipText("history of the last actions");
      logList.setVisibleRowCount(10);
      logList.setValueIsAdjusting(true);
      logList.setFont(FONT);
      logList.setCellRenderer(new MyCellRenderer2(wrapperMap));

      JScrollPane scrollPane = new JScrollPane(logList);
      add(scrollPane);

      logList.addListSelectionListener(new ListSelectionListener() {

         @Override
         public void valueChanged(ListSelectionEvent e) {
            if (!e.getValueIsAdjusting()) {
               JList<LogType> list = (JList<LogType>) e.getSource();
               LogType selection = list.getSelectedValue();
               String message = String.format("Selected LogType: %s", selection);
               JOptionPane.showMessageDialog(MainWindow2.this, message);
            }
         }
      });

   }


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

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

class MyCellRenderer2 extends DefaultListCellRenderer {
   private static final long serialVersionUID = 1L;
   private static final Color DEFAULT_BG = Color.WHITE;
   private static final Color SELECTED_BG = Color.LIGHT_GRAY;
   private Map<LogType, LogWrapper> wrapperMap;

   public MyCellRenderer2(Map<LogType, LogWrapper> wrapperMap) {
      setOpaque(true);
      this.wrapperMap = wrapperMap;
   }

   @Override
   public Component getListCellRendererComponent(JList<?> list, Object value,
         int index, boolean isSelected, boolean cellHasFocus) {
      LogType lt = (LogType) value;
      LogWrapper logWrapper = wrapperMap.get(lt);
      String text = logWrapper.getText();

      Color background = isSelected ? SELECTED_BG : DEFAULT_BG;
      Color foreground = logWrapper.getForeground();
      Font font = list.getFont().deriveFont(logWrapper.getFontStyle());

      Component c = super.getListCellRendererComponent(list, text, index,
            isSelected, cellHasFocus);

      c.setForeground(foreground);
      c.setBackground(background);
      c.setFont(font);

      return c;
   }
}

class LogWrapper {
   private String text;
   private int fontStyle;
   private Color foreground;

   public LogWrapper(String text, int fontStyle, Color foreground) {
      this.text = text;
      this.fontStyle = fontStyle;
      this.foreground = foreground;
   }

   public String getText() {
      return text;
   }

   public int getFontStyle() {
      return fontStyle;
   }

   public Color getForeground() {
      return foreground;
   }

}

如果您尝试为 JList 中的每一行设置唯一的文本,那么

  1. 使 JList 的泛型类型及其模型成为包装类。
  2. 更改包装器以包含枚举。
  3. 为添加到列表中的每个项目创建一个唯一的包装器实例,其中一个具有唯一的文本字段值。如果您只想设置一次字体和颜色,则复制构造函数可以很好地工作。

例如(代码示例 3):

import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.util.EnumMap;
import java.util.Map;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class MainWindow3 extends JPanel {
   private static final long serialVersionUID = 1L;
   private static final Font FONT = new Font(Font.DIALOG, Font.PLAIN, 12);
   private static DefaultListModel<LogWrapper3> logListModel = new DefaultListModel<>();
   private static JList<LogWrapper3> logList = new JList<>(logListModel);

   public MainWindow3() {
      Map<LogType, LogWrapper3> wrapperMap = new EnumMap<>(LogType.class);
      wrapperMap.put(LogType.ACTION, new LogWrapper3("Action", Font.PLAIN, Color.BLUE, LogType.ACTION));
      wrapperMap.put(LogType.COMMENT, new LogWrapper3("Comment", Font.PLAIN, Color.DARK_GRAY, LogType.COMMENT));
      wrapperMap.put(LogType.ERROR, new LogWrapper3("Error", Font.BOLD, Color.RED, LogType.ERROR));
      wrapperMap.put(LogType.READ_INFO, new LogWrapper3("Read Info", Font.ITALIC, Color.MAGENTA, LogType.READ_INFO));
      wrapperMap.put(LogType.PARAM_ERROR, new LogWrapper3("Parameter Error", Font.BOLD, Color.ORANGE, LogType.PARAM_ERROR));

      for (int i = 0; i < 8; i++) {
         for (int j = 0; j < LogType.values().length; j++) {
            LogType logType = LogType.values()[j];
            LogWrapper3 wrapper = new LogWrapper3(wrapperMap.get(logType));
            String text = "Type : " + logType.toString() + " - Loop : " + i;
            wrapper.setText(text);
            logListModel.addElement(wrapper);
         }
      }

      logList.setToolTipText("history of the last actions");
      logList.setVisibleRowCount(10);
      logList.setValueIsAdjusting(true);
      logList.setFont(FONT);
      logList.setCellRenderer(new MyCellRenderer3());

      JScrollPane scrollPane = new JScrollPane(logList);
      add(scrollPane);

      logList.addListSelectionListener(new ListSelectionListener() {

         @Override
         public void valueChanged(ListSelectionEvent e) {
            if (!e.getValueIsAdjusting()) {
               JList<LogWrapper3> list = (JList<LogWrapper3>) e.getSource();
               LogWrapper3 selection = list.getSelectedValue();
               String message = String.format("Selected LogType: %s", selection.getLogType());
               JOptionPane.showMessageDialog(MainWindow3.this, message);
            }
         }
      });
   }

   private class MyCellRenderer3 extends DefaultListCellRenderer {
      private static final long serialVersionUID = 1L;
      private final Color DEFAULT_BG = Color.WHITE;
      private final Color SELECTED_BG = Color.LIGHT_GRAY;

      public MyCellRenderer3() {
         setOpaque(true);
      }

      @Override
      public Component getListCellRendererComponent(JList<?> list, Object value,
            int index, boolean isSelected, boolean cellHasFocus) {
         LogWrapper3 ltw = (LogWrapper3) value;

         Color background = isSelected ? SELECTED_BG : DEFAULT_BG;
         Color foreground = ltw.getForeground();
         Font font = list.getFont().deriveFont(ltw.getFontStyle());

         Component c = super.getListCellRendererComponent(list, ltw.getText(), index,
               isSelected, cellHasFocus);

         c.setForeground(foreground);
         c.setBackground(background);
         c.setFont(font);

         return c;
      }
   }

   private class LogWrapper3 {
      private String text;
      private int fontStyle;
      private Color foreground;
      private LogType logType;

      public LogWrapper3(String text, int fontStyle, Color foreground, LogType logType) {
         this.text = text;
         this.fontStyle = fontStyle;
         this.foreground = foreground;
         this.logType = logType;
      }

      // copy constructor
      public LogWrapper3(LogWrapper3 lw3) {
         this.text = lw3.text;
         this.fontStyle = lw3.fontStyle;
         this.foreground = lw3.foreground;
         this.logType = lw3.logType;
      }

      public String getText() {
         return text;
      }

      public void setText(String text) {
         this.text = text;
      }

      public int getFontStyle() {
         return fontStyle;
      }

      public Color getForeground() {
         return foreground;
      }

      public LogType getLogType() {
         return logType;
      }

   }

   enum LogType {
      ERROR("Error"), COMMENT("Comment"), READ_INFO("Read Info"), ACTION("Action"), PARAM_ERROR("Param Error"); 
      private String text;

      private LogType(String text) {
         this.text = text;
      }

      public String getText() {
         return text;
      }
   };


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

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}
于 2015-07-16T16:45:08.453 回答