如何在JTable示例颜色单元格编号(2,2)中为特定单元格着色?

时间:2013-06-04 12:13:22

标签: java swing jtable renderer tablecellrenderer

我有这个代码,我想用不同的颜色为每个单元格着色,例如我想要用红色和单元格1,2用浅红色等单元格颜色1,1等等。如何可能?我去了通过许多例子,但所有这些例子都展示了如何在鼠标点击或上面点亮一个单元格,我想要它。请提前感谢。

package test;

public class ModelJTable extends JFrame {
    private DefaultTableModel model;

    private JTable table;

    public ModelJTable() throws IOException {
        super();
        model = new DefaultTableModel();
        model.addColumn("price");
        model.addColumn("quantity");
        model.addColumn("buy");
        model.addColumn("sell");
        String array[][] = new String[6][6];
        array[0][0] = "35";
        array[0][1] = "1";
        array[0][2] = "2";
        array[1][0] = "34";
        array[1][1] = "2";
        array[1][2] = "3";
        array[2][0] = "37";
        array[2][1] = "2";
        array[2][2] = "6";
        array[3][0] = "33";
        array[3][1] = "7";
        array[3][2] = "8";
        array[4][0] = "34";
        array[4][1] = "9";
        array[4][2] = "4";
        array[5][0]="35";
        array[5][1]="9";
        array[5][2]="6";

        String mainarray[][] = new String[6][6];
                //copy all elements of array to mainarray


        for(int i=0;i<5;i++)
        {
            String temp[]={""};
            model.addRow(temp);
        }
        for (int i = 5; i < 10; i++) {
            model.insertRow(i, array[i-5]);
            // System.out.print(mainarray[i][j]+" ");
        }
        table = new JTable(model);

        JTextField textBox=new JTextField();
        TableColumn soprtColumn=table.getColumnModel().getColumn(1);

        soprtColumn.setCellEditor(new DefaultCellEditor (textBox));

        table.setCellSelectionEnabled(true);

        textBox.setBackground(Color.RED);
        JPanel inputPanel = new JPanel();
        inputPanel.add(addButton);
        inputPanel.add(removeButton);
        Container container = getContentPane();
        container.add(new JScrollPane(table), BorderLayout.CENTER);
        container.add(inputPanel, BorderLayout.NORTH);

        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(400, 300);
        setVisible(true);
    }

        public static void main(String args[]) throws IOException {
        new ModelJTable();
    }
     public Component getTableCellRendererComponent
     (JTable table, Object value, boolean isSelected,
     boolean hasFocus, int row, int column) 
  {
      Component cell = model.getTableCellRendererComponent
         (table, value, isSelected, hasFocus, row, column);
      if( value instanceof Integer )
      {
          Integer amount = (Integer) value;
          if( amount.intValue() < 0 )
          {
              cell.setBackground( Color.red );
              // You can also customize the Font and Foreground this way
              // cell.setForeground();
              // cell.setFont();
          }
          else
          {
              cell.setBackground( Color.white );
          }
      }
      return cell;
  }
}

1 个答案:

答案 0 :(得分:2)

  • 有一些错误,我无法发表评论

  • if (isRowSelected(row) && isColumnSelected(column)) {更改为if ((row == 2) && (column == 2)) {(如果行数/列数大于......则必须先测试),然后

enter image description here

来自代码

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.LineBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.*;

public class RemoveAddRows extends JFrame {

    private static final long serialVersionUID = 1L;
    private Object[] columnNames = {"Type", "Company", "Shares", "Price"};
    private Object[][] data = {
        {"Buy", "IBM", Integer.valueOf(1000), Double.valueOf(80.50)},
        {"Sell", "MicroSoft", Integer.valueOf(2000), Double.valueOf(6.25)},
        {"Sell", "Apple", Integer.valueOf(3000), Double.valueOf(7.35)},
        {"Buy", "Nortel", Integer.valueOf(4000), Double.valueOf(20.00)}
    };
    private JTable table;
    private DefaultTableModel model;
    private javax.swing.Timer timer = null;

    public RemoveAddRows() {
        model = new DefaultTableModel(data, columnNames) {
            private static final long serialVersionUID = 1L;

            @Override
            public Class getColumnClass(int column) {
                return getValueAt(0, column).getClass();
            }
        };
        table = new JTable(model) {
            private static final long serialVersionUID = 1L;

            @Override
            public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
                Component c = super.prepareRenderer(renderer, row, column);
                if (isRowSelected(row) && isColumnSelected(column)) {
                    ((JComponent) c).setBorder(new LineBorder(Color.red));
                }
                return c;
            }
        };
        DefaultTableCellRenderer stringRenderer = (DefaultTableCellRenderer) table.getDefaultRenderer(String.class);
        stringRenderer.setHorizontalAlignment(SwingConstants.CENTER);
        ListSelectionModel rowSelMod = table.getSelectionModel();
        rowSelMod.addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                int row = table.getSelectedRow();
                int col = table.getSelectedColumn();
                String str = "Selected Row(s): ";
                int[] rows = table.getSelectedRows();
                for (int i = 0; i < rows.length; i++) {
                    str += rows[i] + " ";
                }
                str += "Selected Column(s): ";
                int[] cols = table.getSelectedColumns();
                for (int i = 0; i < cols.length; i++) {
                    str += cols[i] + " ";
                }
                str += "Selected Cell: " + table.getSelectedRow() + ", " + table.getSelectedColumn();
                System.out.println(str);
                Object value = table.getValueAt(row, col);
                System.out.println(String.valueOf(value));
            }
        });
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane);
        JButton button1 = new JButton("Remove all rows");
        button1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                if (model.getRowCount() > 0) {
                    for (int i = model.getRowCount() - 1; i > -1; i--) {
                        model.removeRow(i);
                    }
                }
                System.out.println("model.getRowCount() --->" + model.getRowCount());
            }
        });
        JButton button2 = new JButton("Add new rows");
        button2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                start();
            }
        });
        JPanel southPanel = new JPanel();
        southPanel.add(button1);
        southPanel.add(button2);
        add(southPanel, BorderLayout.SOUTH);
    }

    private void start() {
        timer = new javax.swing.Timer(2500, updateCol());
        timer.start();
    }

    public Action updateCol() {
        return new AbstractAction("text load action") {
            private static final long serialVersionUID = 1L;

            @Override
            public void actionPerformed(ActionEvent e) {
                DefaultTableModel model = (DefaultTableModel) table.getModel();
                Object[] data0 = {"Buy", "IBM", Integer.valueOf(1000), Double.valueOf(80.50)};
                model.addRow(data0);
                Object[] data1 = {"Sell", "MicroSoft", Integer.valueOf(2000), Double.valueOf(6.25)};
                model.addRow(data1);
                Object[] data2 = {"Sell", "Apple", Integer.valueOf(3000), Double.valueOf(7.35)};
                model.addRow(data2);
                Object[] data3 = {"Buy", "Nortel", Integer.valueOf(4000), Double.valueOf(20.00)};
                model.addRow(data3);
                System.out.println("model.getRowCount() --->" + model.getRowCount());
                timer.stop();
                int rowIndex = table.getRowCount() - 1;
                table.changeSelection(rowIndex, 0, false, false);
            }
        };
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                RemoveAddRows frame = new RemoveAddRows();
                frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }
}