Follow along with the video below to see how to install our site as a web app on your home screen.
Note: This feature may not be available in some browsers.
class MyTableCellRenderer extends DefaultTableCellRenderer
{
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected,boolean hasFocus,int row, int col)
{
Component comp = super.getTableCellRendererComponent(table,
value, isSelected, hasFocus, row, col);
setBackground(/*color*/);
return comp;
}
}
bassman said:Derive a from DefaultTableCellRenderer and override getTableCellRendererComponent().
Code:class MyTableCellRenderer extends DefaultTableCellRenderer { public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,boolean hasFocus,int row, int col) { Component comp = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col); setBackground(/*color*/); return comp; } }
Set the renderer using JTable.setDefaultRenderer().
import java.util.*;
import java.util.Vector.*;
import javax.swing.*;
import javax.swing.table.*;
import java.awt.GridLayout;
import java.awt.Dimension;
public class View extends JFrame {
private JFrame myFrame;
private JTabbedPane tabbedPane;
private JTable myTable;
private JScrollPane scrollPane;
public View( int size ) {
super("Changes");
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName( ) );
} catch ( Exception e ) { System.out.println( e.getMessage( ) ); }
myTable = new JTable( size, 2 );
myTable.setRowHeight( 20 );
scrollPane = new JScrollPane( myTable, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED );
scrollPane.setPreferredSize( new Dimension( 640, 480 ) );
}
public void addLine( String whichSide, int whichRow, String content ) {
if( whichSide.equals( "source" ) ) {
myTable.setValueAt( content,whichRow ,0 );
} else {
myTable.setValueAt( content,whichRow ,1 );
}
}
public void showAll( ) {
this.getContentPane( ).add( scrollPane );
this.setSize( 640,480 );
this.setLocationRelativeTo( null );
this.setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );
this.setVisible( true );
}
}
Ok, i have another problem then:bassman said:Having an external method (addLine) is not the way to do this. JTable colors each cell when it is rendered. By using an overridden DefaultTableCellRenderer, you hook directly in to the cell rendering in a nice, encapsulated, object-oriented way.