3

我正在使用 Java 中的 Swing 库编写应用程序。我有一个扩展的表格组件,JTable在这个组件中我覆盖了方法getTableCellRendererComponent,因为我为表格的单元格着色。我有一个自定义表格模型(从默认表格模型扩展而来),并且表格组件本身已添加到 JPanel。这一切都有效。

现在我想在这个表中添加一些功能来让单元格闪烁。潜在地,一次可以有多个单元格闪烁,即(第 1 行,第 2 列)和(第 3 行,第 4 列)处的单元格。

这可能吗?任何可以让我开始的提示将不胜感激。

4

1 回答 1

3

我找到一篇文章来回答你:

http://www.devx.com/DevX/10MinuteSolution/17167/0/page/1

该页面提供下载源代码。

基本上它使用以下方法通知表及时更新单元格。

JTable.tableChanged(new TableModelEvent(table.getModel(), firstRow, lastRow, column));

看了他的代码,我整理了一个他的代码比较简单的版本,你可以改我的代码或者使用他的代码(更优雅也更复杂)。

public class FlashCellTable
{
    public static Color color;

    public static void main(String[] args)
    {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setSize(800, 600);

        final JTable table = new JTable(4, 4);
        table.setDefaultRenderer(Object.class, new MyFlashingCellRenderer());
        table.setValueAt("Flashing", 0, 0);
        frame.getContentPane().add(new JScrollPane(table));

        final long startTime = System.currentTimeMillis();

        Thread thread = new Thread()
        {
            @Override
            public void run()
            {
                while (true)
                {
                    long now = System.currentTimeMillis();
                    long second = (now - startTime) / 1000;
                    color = second / 2 * 2 == second ? Color.red : Color.blue;

                    System.out.println("FlashCellTable.run");

                    SwingUtilities.invokeLater(new Runnable()
                    {
                        public void run()
                        {
                            table.tableChanged(new TableModelEvent(table.getModel(), 0, 0, 0));  
                        }
                    });
                    try
                    {
                        Thread.sleep(1000);
                    }
                    catch(InterruptedException e)
                    {
                        e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                    }
                }
            }
        };

        thread.start();

        frame.setVisible(true);
    }

    public static class MyFlashingCellRenderer extends DefaultTableCellRenderer
    {
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
                                                       int row, int column)
        {
            JLabel label =
                (JLabel)super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

            if ("Flashing".equals(value))
            {
                label.setBackground(color);
            }
            else
            {
                label.setBackground(Color.white);
            }
            return label;
        }
    }
}
于 2012-06-08T07:13:01.817 回答