我想在Jtable Java中为我的Cell着色?

时间:2016-06-26 22:57:40

标签: java jtable

我想在Jtable Java中为我的Cell着色?像这样:图像:

http://i.stack.imgur.com/yuzZR.png

可以帮我谢谢!

我上次尝试的代码

import javax.swing.*;

import javax.swing.table.AbstractTableModel;

import javax.swing.table.DefaultTableCellRenderer;

import java.awt.BorderLayout;

import java.awt.Color;

import java.awt.Component;

public class Main
{
        /**
         * @param args
         */
        public static void main(String[] args)
        {
                JFrame frame = new JFrame();
                frame.add(new JComboxTable(), BorderLayout.NORTH);
                frame.setVisible(true);
                frame.setSize(300, 300);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }
}

class JComboxTable extends JTable
{

        public static JComboBox cb;

        public JComboxTable()
        {
                TableModel tree = new TableModel();
                TableRenderer render = new TableRenderer();
                setModel(tree);
                setDefaultRenderer(Object.class, render);
                tree.fireTableDataChanged();
        }

}

class TableModel extends AbstractTableModel
{

        public int getColumnCount()
        {
                return 2;
        }

        public int getRowCount()
        {
                return 5;
        }

        @Override
        public Class<?> getColumnClass(int columnIndex)
        {
                if (columnIndex == 0)
                {
                        return String.class;
                }
                else
                {
                        return Color.class;
                }
        }

        public Object getValueAt(int rowIndex, int columnIndex)
        {
                if (columnIndex == 0)
                {
                        return "Salut" + rowIndex;
                }
                else
                {
                        if( ( rowIndex % 2 ) == 0 )
                        {
                                return  Color.RED ;
                        }else
                        {
                                return  Color.BLUE ;
                        }
                }
        }

}

class TableRenderer extends DefaultTableCellRenderer
{

        public Component getTableCellRendererComponent(JTable table, Object value,
                        boolean isSelected, boolean hasFocus, int row, int column)
        {
                if (value instanceof Color)
                {
                        setBackground((Color) value);
                        setText("");
                }
                else
                {
                        setBackground( (Color)table.getModel().getValueAt(row, 1) );
                        setText(  (String)value );
                }

                return this;
        }

}
}

1 个答案:

答案 0 :(得分:0)

使用自定义渲染器。

阅读Using Custom Renderers上的Swing教程中的部分以获取工作示例。