如何使特定标签在JList中闪烁

时间:2012-05-19 22:38:26

标签: java swing jlabel jlist renderer

我设法将面板用作JList的单元格渲染组件。并且面板中包含的闪烁标签本身就可以正常工作。但是当我在渲染到列表后,标签停止闪烁。

我通过刷新列表以一定的间隔工作,以便能够看到闪烁,但是这次列表中的所有标签都开始闪烁(我只希望列表中的某些标签满足条件闪烁)。我已经钻研了几个小时尝试解决它,但机会看起来很暗淡。

我的问题在于两层:

  1. 为什么自包含blink-label-prove面板需要JList刷新才能查看眨眼?
  2. 为什么在渲染过程中没有单独标出特定标签会导致列表中的所有标签唱歌和跳舞?

1 个答案:

答案 0 :(得分:3)

SSCCE对我有用:

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

@SuppressWarnings("serial")
public class BlinkingLabelInList extends JPanel {
   public static final Color FLASH_COLOR = Color.red;
   public static final int TIMER_DELAY = 500;
   private String[] data = {"Mon", "Tues", "Wed", "Thurs", "Fri"};
   private JList list = new JList(data);
   public Color cellColor = null;


   public BlinkingLabelInList() {
      add(new JScrollPane(list));
      list.setCellRenderer(new MyListCellRenderer());
      new Timer(TIMER_DELAY, new TimerListener()).start();
   }

   private class TimerListener implements ActionListener {
      @Override
      public void actionPerformed(ActionEvent e) {
         cellColor = (cellColor == null) ? FLASH_COLOR : null;
         list.repaint();
      }
   }

   private class MyListCellRenderer extends DefaultListCellRenderer {
      @Override
      public Component getListCellRendererComponent(JList list,
            Object value, int index, boolean isSelected, boolean cellHasFocus) {
         Component cellRenderer = super.getListCellRendererComponent(list, value, index, isSelected,
               cellHasFocus);
         if (isSelected || cellHasFocus) {
            cellRenderer.setForeground(cellColor );
         } else {
            cellRenderer.setForeground(null);
         }
         return cellRenderer;
      }

   }

   private static void createAndShowGui() {
      BlinkingLabelInList mainPanel = new BlinkingLabelInList();

      JFrame frame = new JFrame("BlinkingLabelInList");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

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