java开发渲染jtable 根据某个单元格中的值,渲染单元格所在行
我现在有个8列的表格,我通过判断表格第8列的值是否等于1,然后如果等于1,则该行为红色另外我对表头进行排序的时候,渲染的颜色该是哪行还是哪行...
我现在有个8列的表格,我通过判断表格第8列的值是否等于1,然后如果等于1 ,则该行为红色
另外我对表头进行排序的时候,渲染的颜色该是哪行还是哪行 展开
另外我对表头进行排序的时候,渲染的颜色该是哪行还是哪行 展开
展开全部
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
public class TableFrame extends JFrame
{
private static final long serialVersionUID = 1L;
private static final int COLNUM = 8;
private static final String[] NAMES = new String[COLNUM];
private static final String[][] DATA = new String[2 * COLNUM][COLNUM];
private static JTable tableView = null;
public TableFrame ( String title )
{
randomTester ();
this.setTitle (title);
}
private void randomTester ()
{
for ( int i = 0; i < NAMES.length; i++ )
{
NAMES[i] = "COL" + ( i + 1 );
}
for ( int i = 0; i < DATA.length; i++ )
{
for ( int j = 0; j < DATA[i].length; j++ )
{
DATA[i][j] = (int) ( Math.random () * 5 + 1 ) + "";
}
}
}
private static void createTable ( TableFrame tc )
{
AbstractTableModel dataModel = new AbstractTableModel ()
{
private static final long serialVersionUID = 1L;
public int getColumnCount ()
{
return NAMES.length;
}
public int getRowCount ()
{
return DATA.length;
}
public Object getValueAt ( int row, int col )
{
return DATA[row][col];
}
public String getColumnName ( int column )
{
return NAMES[column];
}
};
tableView = new JTable (dataModel);
tableView.setDefaultRenderer (Object.class, new TableCellRenderer ()
{
@Override
public Component getTableCellRendererComponent ( JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column )
{
Component render =
new DefaultTableCellRenderer ().getTableCellRendererComponent (table, value, isSelected,
hasFocus, row, column);
if ("1".equals (table.getValueAt (row, NAMES.length - 1)))
{
render.setBackground (Color.RED);
}
return render;
}
});
tableView.setRowSorter (new TableRowSorter<TableModel> (dataModel));
JScrollPane scrollpane = new JScrollPane (tableView);
scrollpane.setPreferredSize (new Dimension (500, 400));
tc.add (scrollpane);
}
private static void initFrame ( TableFrame tc )
{
tc.setLayout (new FlowLayout (FlowLayout.LEFT));
tc.setSize (500, 400);
tc.pack ();
tc.setResizable (false);
tc.setLocationRelativeTo (null);
tc.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
tc.setVisible (true);
}
public static void main ( String[] args )
{
TableFrame tc = new TableFrame ("TableFrame");
createTable (tc);
initFrame (tc);
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询
广告 您可能关注的内容 |