如何设置JTable列和行颜色?

时间:2010-08-23 15:21:17

标签: java swing jtable

如何设置JTable列和行颜色?

3 个答案:

答案 0 :(得分:3)

这是一个简短的example

import java.awt.Color;
import java.awt.Component;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;

public class JTableExample extends JFrame {

 String data[][] = {{"John", "Sutherland", "Student"},
   {"George", "Davies", "Student"},
   {"Melissa", "Anderson", "Associate"},
   {"Stergios", "Maglaras", "Developer"},
 };

 String fields[] = {"Name", "Surname", "Status"};

 public static void main( String[] argv ) {
  JTableExample myExample = new JTableExample( "JTable Example" );
 }

 /**
  * @param title
  */
 public JTableExample( String title ) {
  super( title );
  setSize( 150, 150 );
  addWindowListener( new WindowAdapter() {
   public void windowClosing( WindowEvent we ) {
    dispose();
    System.exit( 0 );
   }
  } );
  init();
  pack();
  setVisible( true );
 }

 private void init() {

  final CustomCellRenderer renderer = new CustomCellRenderer();        
  JTable jt = new JTable( data, fields ) {

   @Override
   public TableCellRenderer getCellRenderer(int row, int column) {
    // TODO Auto-generated method stub
    return renderer;
   }

  };
  JScrollPane pane = new JScrollPane( jt );
  getContentPane().add( pane );
 }


 /**
  * @author suhas
  *
  */
 private class CustomCellRenderer extends DefaultTableCellRenderer {

  /* (non-Javadoc)
   * @see javax.swing.table.DefaultTableCellRenderer#getTableCellRendererComponent(javax.swing.JTable, java.lang.Object, boolean, boolean, int, int)
   */
  public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus, int row, int column) {

   Component rendererComp = super.getTableCellRendererComponent(table, value, isSelected, hasFocus,
     row, column);

   //Set foreground color
   rendererComp.setForeground(Color.red);

   //Set background color
   rendererComp .setBackground(Color.blue);

   return rendererComp ;
  }

 }

}

答案 1 :(得分:2)

从一个心不在焉的提问者那里回答一个模糊的问题需要一些善意(和空闲的时间)。

对于列,您可以设置在列上扩展DefaultTableCellRenderer(扩展JLabel)的单元格渲染器,然后设置渲染器的前景和背景。

对于行,您必须在单元格渲染器的getTableCellRendererComponent中执行此操作。

如果您需要超出平凡的任何内容(例如备用行背景),则应使用灵活的自定义渲染器。有无数的免费和商业桌面组件提供着色和JTable应该具有的一切,例如JIDE Grids(不是免费但超级强大)。

答案 2 :(得分:0)

DefaultTableCellRenderer rendar1 = new DefaultTableCellRenderer();
    rendar1.setForeground(Color.red);

    jTable1.getColumnModel().getColumn(0).setCellRenderer(rendar1);

将该列的颜色更改为构造函数