JTable.setDefaultRenderer
HI,
I am trying to sett up a custom renderer for my table, however am having a problem in that the renderer code is never executed. In the following code I am trying to create a custom renderer for all table elements that are of the String class, and register the renderer as such, however when executing the code, I never see the System.out.println statement that is in the renderer's getTableCellRendererComponent method. Please help. Test code is as follows:
import java.awt.Component;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.Dimension;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.JFrame;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellRenderer;
public class TableCellRenderingTest extends JTable {
private static final String [] columnNames = {
"Column 1",
"Column 2",
"Column 3"
private static String [] [] data = {
{"1,1", "1,2", "1,3"},
{"2,1", "2,2", "2,3"}
public TableCellRenderingTest() {
super();
setModel(new MyModel());
setDefaultRenderer(String.class, new MyRenderer());
public class MyModel extends AbstractTableModel {
public String getColumnName(int col) {
return columnNames[col];
public int getRowCount() {
return data.length;
public int getColumnCount() {
return columnNames.length;
public Object getValueAt(int row, int col) {
return data [row] [col];
public class MyRenderer extends JLabel implements TableCellRenderer {
public MyRenderer() {
super();
public Component getTableCellRendererComponent(JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column) {
// **********THE FOLLOWING STATEMENT IS NEVER PRINTED******//
System.out.println("ABOUT TO RUN RENDERER CODE");
setText((String) value);
return this;
public static void main(String [] args) {
JTable table = new TableCellRenderingTest();
JFrame f = new JFrame();
f.getContentPane().add(table);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
f.pack();
f.setSize(new Dimension(600, 600));
f.show();
Just tried that as well w/o any luck.....see the slightly modified code below:
import java.awt.Component;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.Dimension;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.JFrame;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
public class TableCellRenderingTest2 extends JTable {
private static final String [] columnNames = {
"Column 1",
"Column 2",
"Column 3"
private static String [] [] data = {
{"1,1", "1,2", "1,3"},
{"2,1", "2,2", "2,3"}
public TableCellRenderingTest2() {
super();
setModel(new MyModel());
TableColumnModel columnModel = getColumnModel();
TableColumn column0 = columnModel.getColumn(0);
column0.setCellRenderer(new MyRenderer());
public class MyModel extends AbstractTableModel {
public String getColumnName(int col) {
return columnNames[col];
public int getRowCount() {
return data.length;
public int getColumnCount() {
return columnNames.length;
public Object getValueAt(int row, int col) {
return data [row] [col];
public class MyRenderer extends JLabel implements TableCellRenderer {
public MyRenderer() {
super();
public Component getTableCellRendererComponent(JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column) {
System.out.println("ABOUT TO RETRIEVE RENDERER COMPONENT");
setText((String) value);
return this;
public static void main(String [] args) {
JTable table = new TableCellRenderingTest();
JFrame f = new JFrame();
f.getContentPane().add(table);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
f.pack();
f.setSize(new Dimension(600, 600));
f.show();
Similar Messages
-
JTable setDefaultRenderer - how to update
Hey folks,
when I do this:
Table.setDefaultRenderer(Object.class, new SelectedRenderer());I usually did a:
Table.updateUI();to make the changes visible. But isn't that the wrong way?? Since the Look and Feel hasn't changed. Is there another way to do the visualization update rather than reloading from UIManager?
This assumes that the Table is already displayed on a JPanel and i need to switch between Renderers.
Best RegardsEach of the fireXXX methods (leaving aside the structure one) tells JTable that some region (cell, row, everything) needs repainting. It works out (visible scroll region + fireXXX granularity) what cells it needs to paint and then goes through the process of getting the renderer and calling its getTableCellRendererComponent method for each one.
The renderer is responsible for all aspects of cell formatting (bg/fg colours, font, style, icon anything you choose to code in it). The model value for the cell will be queried during this process because that is one of the renderer's arguments, so you see as many TableModel.getValueAt() calls as you do getTableCellRendererComponent ones.
The complex components like JTable and JTree in particular, may cache certain things about the model state, so just forcing a repaint some other way will not always work. Their event model is designed to communicate what (to some specific level) is now stale about the model data.
Hope that's OK. -
Problem with JTable.setDefaultRenderer()
Hi,
I try to set the default renderer of a table for Integer type in the following way:
table.setDefaultRenderer(Integer.TYPE, new IntegerRenderer());
This line doesn't work. However the following line do work:
table.setDefaultRenderer(new Integer(0).getClass(), new IntegerRenderer());
Can anyone tell me why using the static instance doesn't work?
Thanks,
ShaiI don't know why it isn't working for you. I do the same thing with Double.class in one of my tables and it works fine.
-
Disabling the border on JTable cell renderer
Hello all
I've developed a JTable that doesn't allow cell editing and only allows single-row selection. It works fine, I've allowed the user to press <tab> to select the next row or click the mouse to select any row. The row selected is high-lighted and I'm happy with how it works.
However:
Due to the single-row selection policy, it doesn't make sense to display a border around any cell that has been clicked. I would therefore like to prevent the JTable from displaying a border on any cell the user has clicked.
I've checked out the API documentation for JTable and the closest I've been able to get is to construct a DefaultTableCellRenderer and then use JTable.setDefaultRenderer. The problem is I don't know how to set the DefaultTableCellRenderer to NOT display a border when selected.
I can see a method called getTableCellRendererComponent which takes parameters that seemingly return a rendering component, but should I specify isSelected = true and isFocus = true? And what should I do once I have the Component? I've tried casting it to a JLabel and setBorder(null) on it, but the behaviour of the table remains the same.
I've tried all sorts of things but to no avail. I'm finding it all a bit confusing...
Why oh why isn't there simply a setTableCellRendererComponent()? ;)JTable can potentially use multiple renderers based on the type of data in each column, so you would need to create multiple custom renderers using the above approach. The following should work without creating custom renderers:
table = new JTable( ... )
public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
Component c = super.prepareRenderer(renderer, row, column);
((JComponent)c).setBorder(null);
return c;
}; -
Hi guys,
I'm having an issue with a JTable, I hope you can help me.
Last cells of each row is a JButton and my issue is with click on that button.
In fact, it's required clicking two times to run code linked to listener for the same button.
What I need is clicking just one time to run code, not two times.
This is code to build Table:
private JTable getJTable() {
if (jTable == null) {
jTable = new JTable();
jTable.setModel(new MyTableModel());
final MyTableModel tabella = (MyTableModel) jTable.getModel();
Vector<String> nameColumn = new Vector<String>();
nameColumn.addElement("Cliente");
nameColumn.addElement("Data");
nameColumn.addElement("Esito");
nameColumn.addElement("Immagine");
nameColumn.addElement("Dettagli");
tabella.setColumnIdentifiers(nameColumn);
tabella.setElencoDiagnosi(true);
final Vector<Diagnosi> elencoDiagnosi = gestioneDiagnosi.selectAllDiagnosi();
jTable.getColumn("Dettagli").setCellRenderer(new PanelRender());
jTable.getColumn("Dettagli").setCellEditor(new PanelEditor());
jTable.getColumn("Immagine").setCellRenderer(new PanelRender());
jTable.getColumn("Immagine").setCellEditor(new PanelEditor());
jTable.setRowHeight(36); //Metto un altezza che mi consenta di vedere tutto il bottone
JButton[] arrayButtonDettagli = new JButton[elencoDiagnosi.size()];
JButton[] arrayButtonImmagini = new JButton[elencoDiagnosi.size()];
for (int i=0;i<elencoDiagnosi.size(); i++)
final int contatore=i;
arrayButtonDettagli[i] = new JButton("Elenco Dettagli");
arrayButtonDettagli.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
Diagnosi diagnosi=elencoDiagnosi.get(contatore);
GUIElencoDiagnosi.this.dispose();
GUIModificaDiagnosi modificaDiagnosi =
new GUIModificaDiagnosi(OrthoLabMain.listaUtenti,
risultati,diagnosi);
modificaDiagnosi.setVisible(true);
final Diagnosi diagnosi=elencoDiagnosi.get(i);
arrayButtonImmagini[i] = new JButton(new javax.swing.ImageIcon(getClass().getResource("/image/jpg-icon.gif"))) ;
arrayButtonImmagini[i].setSize(36, 36);
arrayButtonImmagini[i].setBackground(Color.WHITE);
arrayButtonImmagini[i].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
JOptionPane.showMessageDialog(null,"","Zoom Immagine",
JOptionPane.INFORMATION_MESSAGE,new ImageIcon(diagnosi.getImmagine()));
Object[] row = new String[4];
row[0]=diagnosi.getCognomeCliente()+" "+diagnosi.getNomeCliente();
String dataviewanno=diagnosi.getData().substring(0, 4);
String dataviewmese=diagnosi.getData().substring(4,6);
String dataviewgiorno=diagnosi.getData().substring(6, 8);
row[1]=dataviewgiorno+"/"+dataviewmese+"/"+dataviewanno;
row[2]=diagnosi.getEsito();
tabella.addRow(row);
tabella.setValueAt(arrayButtonImmagini[i],i, 3);
tabella.setValueAt(arrayButtonDettagli[i], i, 4);
return jTable;
This is code for CellRender and CellEditor (written ad hoc)Cell renderer (PanelRenderer)
public class PanelRender extends DefaultTableCellRenderer {
private static final long serialVersionUID = 1L;
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if(value instanceof JComponent) {
return (JComponent)value;
} else {
return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
Cell Editor (PanelEditor)
public class PanelEditor extends AbstractCellEditor implements TableCellEditor {
private static final long serialVersionUID = 1L;
private JComponent panel = null;
public Object getCellEditorValue() {
return panel;
public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected, int row, int column) {
panel = (JComponent)value;
return panel;
Could you help me?
ThanksThanks Ryan,
I solved my issue with your help. Now I've a bit issue, that is I can't see icon on my button, it seems like toString method is displayed instead icon.
For table renderer I use a new class that implements TableCellRenderer, while for model I use a new class that extends DefaultTableModel.. In the following some code...please help me, icon on button aren't shown! Thanks
private JScrollPane getJScrollPane(Vector<Diagnosi> ris) {
if (jScrollPane == null) {
TableCellRenderer defaultRenderer;
final MyTableModel tabella = (MyTableModel) jTable.getModel();
defaultRenderer = jTable.getDefaultRenderer(JButton.class);
jTable.setDefaultRenderer(JButton.class,
new PanelRender(defaultRenderer));
jTable.getColumn("Immagine").setCellRenderer(defaultRenderer);
jTable.getColumn("Immagine").setCellEditor(new PanelEditor());
jTable.getColumn("Regolo").setCellRenderer(defaultRenderer);
jTable.getColumn("Regolo").setCellEditor(new PanelEditor());
jTable.getColumn("PDF").setCellRenderer(defaultRenderer);
jTable.getColumn("PDF").setCellEditor(new PanelEditor());
jScrollPane.setViewportView(jTable);
return jScrollPane;My Table Model
public class MyTableModel extends DefaultTableModel {
public MyTableModel(Object[][] data, Object[] columnNames) {
super(data, columnNames);
public MyTableModel(){
super();
public boolean isCellEditable(int row, int column) {
if(elencoClienti){
if(column!=5)
return false;
else return true;
else if(elencoDiagnosi){
if(column<3)
return false;
else return true;
else if(clientiLista)
return false;
else if(diagnosiLista){
if(column<3)
return false;
else return true;
else if(clientiPerDiagnosi){
if(column!=3)
return false;
else return true;
else return false;
}Panel Editor
public class PanelEditor extends AbstractCellEditor implements TableCellEditor {
private static final long serialVersionUID = 1L;
private JComponent panel = null;
public Object getCellEditorValue() {
return panel;
public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected, int row, int column) {
panel = (JComponent)value;
return panel;
} -
Shading part of a JTable Cell dependent upon the value of the cell
Hi
Was hoping some one woudl be able to provide some help with this. I'm trying to create a renderer that will "shade" part of a JTable cell's background depending upon the value in the cell as a percentage (E.g. if the cell contains 0.25 then a quarter of the cell background will be shaded)
What I've got so far is a renderer which will draw a rectangle whose width is the relevant percentage of the cell's width. (i.e. the width of the column) based on something similar I found in the forum but the part I'm struggling with is getting it to draw this rectangle in any cell other than the first cell. I've tried using .getCellRect(...) to get the x and y position of the cell to draw the rectangle but I still can't make it work.
The code for my renderer as it stands is:
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;
public class PercentageRepresentationRenderer extends JLabel implements TableCellRenderer{
double percentageValue;
double rectWidth;
double rectHeight;
JTable table;
int row;
int column;
int x;
int y;
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if (value instanceof Number)
this.table = table;
this.row = row;
this.column = column;
Number numValue = (Number)value;
percentageValue = numValue.doubleValue();
rectHeight = table.getRowHeight(row);
rectWidth = percentageValue * table.getColumnModel().getColumn(column).getWidth();
return this;
public void paintComponent(Graphics g) {
x = table.getCellRect(row, column, false).x;
y = table.getCellRect(row, column, false).y;
setOpaque(false);
Graphics2D g2d = (Graphics2D)g;
g2d.fillRect(x,y, new Double(rectWidth).intValue(), new Double(rectHeight).intValue());
super.paintComponent(g);
}and the following code produces a runnable example:
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class PercentageTestTable extends JFrame {
public PercentageTestTable()
Object[] columnNames = new Object[]{"A","B"};
Object[][] tableData = new Object[][]{{0.25,0.5},{0.75,1.0}};
DefaultTableModel testModel = new DefaultTableModel(tableData,columnNames);
JTable test = new JTable(testModel);
test.setDefaultRenderer(Object.class, new PercentageRepresentationRenderer());
JScrollPane scroll = new JScrollPane();
scroll.getViewport().add(test);
add(scroll);
public static void main(String[] args)
PercentageTestTable testTable = new PercentageTestTable();
testTable.pack();
testTable.setVisible(true);
testTable.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}If anyone could help or point me in the right direction, I'd appreciate it.
RuanaeThis is an example I published some while ago -
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
public class Fred120 extends JPanel
static final Object[][] tableData =
{1, new Double(10.0)},
{2, new Double(20.0)},
{3, new Double(50.0)},
{4, new Double(10.0)},
{5, new Double(95.0)},
{6, new Double(60.0)},
static final Object[] headers =
"One",
"Two",
public Fred120() throws Exception
super(new BorderLayout());
final DefaultTableModel model = new DefaultTableModel(tableData, headers);
final JTable table = new JTable(model);
table.getColumnModel().getColumn(1).setCellRenderer( new LocalCellRenderer(120.0));
add(table);
add(table.getTableHeader(), BorderLayout.NORTH);
public class LocalCellRenderer extends DefaultTableCellRenderer
private double v = 0.0;
private double maxV;
private final JPanel renderer = new JPanel(new GridLayout(1,0))
public void paintComponent(Graphics g)
super.paintComponent(g);
g.setColor(Color.CYAN);
int w = (int)(getWidth() * v / maxV + 0.5);
int h = getHeight();
g.fillRect(0, 0, w, h);
g.drawRect(0, 0, w, h);
private LocalCellRenderer(double maxV)
this.maxV = maxV;
renderer.add(this);
renderer.setOpaque(true);
renderer.setBackground(Color.YELLOW);
renderer.setBorder(null);
setOpaque(false);
setHorizontalAlignment(JLabel.CENTER);
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col)
final JLabel label = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
if (value instanceof Double)
v = ((Double)value).doubleValue();
return renderer;
public static void main(String[] args) throws Exception
final JFrame frame = new JFrame("Fred120");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new Fred120());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} -
How to set cell background color for JCheckBox renderer in JTable?
I need to display table one row with white color and another row with customized color.
But Boolean column cannot set color background color.
Here is my codes.
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.table.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.util.TreeSet;
public class BooleanTable extends JFrame
Object[][] data = {{Boolean.TRUE},{Boolean.TRUE},{Boolean.TRUE},{Boolean.TRUE},{Boolean.TRUE},{Boolean.TRUE}};
String[] header = {"CheckBoxes"};
public BooleanTable()
setDefaultCloseOperation( EXIT_ON_CLOSE );
TableModel model = new AbstractTableModel()
public String getColumnName(int column)
return header[column].toString();
public int getRowCount()
return data.length;
public int getColumnCount()
return header.length;
public Class getColumnClass(int columnIndex)
return( data[0][columnIndex].getClass() );
public Object getValueAt(int row, int col)
return data[row][col];
public boolean isCellEditable(int row, int column)
return true;
public void setValueAt(Object value, int row, int col)
data[row][col] = value;
fireTableCellUpdated(row, col);
JTable table = new JTable(model);
table.setDefaultRenderer( Boolean.class, new MyCellRenderer() );
getContentPane().add( new JScrollPane( table ) );
pack();
setLocationRelativeTo( null );
setVisible( true );
public static void main( String[] a )
try
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
catch( Exception e )
new BooleanTable();
private class MyCellRenderer extends JCheckBox implements TableCellRenderer
public MyCellRenderer()
super();
setHorizontalAlignment(SwingConstants.CENTER);
public Component getTableCellRendererComponent(JTable
table, Object value, boolean isSelected, boolean
hasFocus, int row, int column)
if (isSelected) {
setForeground(Color.white);
setBackground(Color.black);
} else {
setForeground(Color.black);
if (row % 2 == 0) {
setBackground(Color.white);
} else {
setBackground(new Color(239, 245, 217));
setSelected( Boolean.valueOf( value.toString() ).booleanValue() );
return this;
}Instead of extending JCheckBox, extend JPanel... put a checkbox in it. (border layout center).
Or better yet, don't extend any gui component. This keeps things very clean. Don't extend a gui component unless you have no other choice.
private class MyCellRenderer implements TableCellRenderer {
private JPanel _panel = null;
private JCheckBox _checkBox = null;
public MyCellRenderer() {
// Create & configure the gui components we need
_panel = new JPanel( new BorderLayout() );
_checkBox = new JCheckBox();
_checkBox.setHorizontalAlignment( SwingConstants.CENTER );
// Layout the gui
_panel.add( _checkBox, BorderLayout.CENTER );
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
if( isSelected ) {
_checkBox.setForeground(Color.white);
_panel.setBackground(Color.black);
} else {
_checkBox.setForeground(Color.black);
if( row % 2 == 0 ) {
_panel.setBackground(Color.white);
} else {
_panel.setBackground(new Color(239, 245, 217));
_checkBox.setSelected( Boolean.valueOf( value.toString() ).booleanValue() );
return _panel;
} -
Image in a JTable (2)
Thanks for the code, it does compile but it does not display the image.
Maybe if you give a look at the whole code it will be easier.
You said to use MyTableRenderer() but maybe you meant MyCellRenderer().
What do you think ?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.event.*;
import java.io.*;
import java.beans.*;
import javax.imageio.*;
public class yearPlannerBean extends JFrame implements ListSelectionListener,ActionListener,Serializable
private String dayNames[] = {"Saturday","Sunday","Monday","Tuesday","Wednesday","Thursday","Friday"};
private String engMonths[] = {"January","February","March","April","May","June","July","August","September","October","November","December"};
private String spaMonths[] = {"Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"};
private String spadays[]={"S�bado", "Domingo", "Lunes", "Martes", "Mi�rcoles", "Jueves", "Viernes"};
private String itaMonths[] = {"Gennaio","Febbraio","Marzo","Aprile","Maggio","Giugno","luglio","Agosto","Settembre","Ottobre","Novembre","Dicembre"};
private String itadays[]={"Sabato","Domenica","Lunedi","Martedi","Mercoledi","Giovedi","Venerdi"};
private Object fieldValues[][];
private String panelTitle;
private JPanel container;
private JPanel languages;
private JPanel choice;
private JTable planner;
private String days[];
private JScrollPane scrollPane;
private int month;
private int noOfDays;
private int year;
private Zellar zell;
private PropertyChangeSupport support;
private Image icon;
private next bbnext;
private previous bbpre;
private JLabel lan;
private JLabel curry;
private JTextField curye;
private JList linlist;
public yearPlannerBean()
panelTitle = ("Year Planner");
setTitle(panelTitle);
setSize(300,300);
month = 0;
noOfDays = 0;
year = 2003;
zell = new Zellar(1,month,year);
container = new JPanel();
container.setLayout(new BorderLayout());
languages = new JPanel();
choice= new JPanel();
lan= new JLabel("Select Language: ");
String[] words={"English","Italian","Spanish"};
JList linlist= new JList(words);
JScrollPane sc =new JScrollPane(linlist);
linlist.addListSelectionListener(this);
planner = new JTable(getFieldValues(),setColumnNames());
planner.setRowHeight(100);
planner.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
planner.setRowSelectionAllowed(true);
planner.setColumnSelectionAllowed(true);
//myTable.setDefaultRenderer(Object.class, new MyTableRenderer());
planner.setDefaultRenderer(Object.class,new MyCellRenderer());
scrollPane = new JScrollPane(planner);
bbnext= new next();
bbpre=new previous();
bbnext.addActionListener(this);
bbpre.addActionListener(this);
getContentPane().setLayout(new BorderLayout());
container.add(scrollPane,BorderLayout.CENTER);
curry= new JLabel("Current Year");
curye= new JTextField(5);
curye.setText(Integer.toString(year));
choice.add(bbpre);
choice.add(bbnext);
languages.add(curry);
languages.add(curye);
languages.add(lan);
languages.add(linlist);
container.add(choice,BorderLayout.SOUTH);
container.add(languages,BorderLayout.NORTH);
setContentPane(container);
pack();
addWindowListener(new WindowAdapter()
public void windowClosing(WindowEvent e)
System.exit(0);
}//End constructor
public String[] setColumnNames()
days = new String[38];
int count = 0;
int index = 0;
for (index = 0; index < 38; index++)
if (index == 0)
days[index] = "";
else
days[index] = dayNames[count];
if (count != 6)
count++;
else
count = 0;
return days;
}//End getColumnNames
public Object[][] getFieldValues()
int countY = 0;
int countX = 0;
String firstDay = "";
int dayInt;
int dayCount = 0;
int tempCount = 0;
fieldValues = new Object[12][38];
for (countX = 0; countX < 38; countX++)
for (countY = 0; countY < 12; countY++)
monthToInt(engMonths[countY]);
firstDay = zell.getFirstDay(month,year);
dayInt = dayToInt(firstDay);
for (month = 1; month < 12; month++)
tempCount = 1;
for (dayCount = dayInt; dayCount < (noOfDays+dayInt); dayCount++)
if (countX == 0)
fieldValues[countY][countX] = engMonths[countY];
else
//fieldValues.setCellRenderer(new acellrenderer());
fieldValues[countY][dayCount]="" + tempCount;//setIcon(new ImageIcon(icon));
tempCount++;
return fieldValues;
}//End getFieldValues
public void monthToInt(String monthIn)
boolean temp = false;
if (monthIn == "January")
month = 1;
noOfDays = 31;
else
if (monthIn == "February")
month = 2;
if ((year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0)))
noOfDays = 29;
else
noOfDays = 28;
else
if (monthIn == "March")
month = 3;
noOfDays = 31;
else
if (monthIn == "April")
month = 4;
noOfDays = 30;
else
if (monthIn == "May")
month = 5;
noOfDays = 31;
else
if (monthIn == "June")
month = 6;
noOfDays = 30;
else
if (monthIn == "July")
month = 7;
noOfDays = 31;
else
if (monthIn == "August")
month = 8;
noOfDays = 31;
else
if (monthIn == "September")
month = 9;
noOfDays = 30;
else
if (monthIn == "October")
month = 10;
noOfDays = 31;
else
if (monthIn == "November")
month = 11;
noOfDays = 30;
else
if (monthIn == "December")
month = 12;
noOfDays = 31;
}//End monthToInt
public int dayToInt(String dayIn)
int dayOut = 0;
if (dayIn == "Saturday")
dayOut = 1;
else
if (dayIn == "Sunday")
dayOut = 2;
else
if (dayIn == "Monday")
dayOut = 3;
else
if (dayIn == "Tuesday")
dayOut = 4;
else
if (dayIn == "Wednesday")
dayOut = 5;
else
if (dayIn == "Thursday")
dayOut = 6;
else
if (dayIn == "Friday")
dayOut = 7;
return dayOut;
}//End dayToInt
/*class acellrenderer extends DefaultTableCellRenderer
public acellrenderer()
super();
public Component getTableCellRendererComponent (JTable planner)
Component component=super.getTableCellRenderer();
String filepa;
filepa="caley.GIF";
ImageIcon nn;
component.setIcon(new ImageIcon(filepa));
return component;
static class MyCellRenderer extends DefaultTableCellRenderer
{ final Icon icon = new ImageIcon("caley.gif");
public MyCellRenderer ()
super();
public void setValue(Object value)
if(value == null)
{ setText("");
setIcon(icon);
else
setText(String.valueOf(value));
public void actionPerformed(ActionEvent event)
Object source=event.getSource();
int a;
if (source==bbnext)
// button next pressed
a=Integer.parseInt(curye.getText());
curye.setText(Integer.toString(a+1));
else
if (source==bbpre)
// button previous pressed
a=Integer.parseInt(curye.getText());
curye.setText(Integer.toString(a-1));
private int getindex(String astring)
int index=-1;
if(astring.toUpperCase().equals("ENGLISH"))
index=0;
else
if (astring.toUpperCase().equals("ITALIAN"))
index=1;
else
index=2;
return index;
public void valueChanged(ListSelectionEvent event)
JList source=(JList)event.getSource();
Object asel;
int index;
if (source==linlist)
asel=linlist.getSelectedValue();
index=getindex((String)asel);
if (index==0)
// set header in English;
else
if (index==1)
// set header in Italian;
else
if (index==2)
// set header in Spanish;
public static void main(String args[])
yearPlannerBean test = new yearPlannerBean();
test.setVisible(true);
}//End Main
}//End classThere are too many unresolved classes in your code for me to use it. Here is a simple example of putting an icon in a table.import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
public class Test extends JFrame {
public Test() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container content = getContentPane();
String[] head = {"One","Two","Three"};
String[][] data = {{"R1-C1","R1-C2","R1-C3"},
{"R1-C1","R1-C2","R1-C3"},
{"R1-C1","R1-C2","R1-C3"}};
JTable jt = new JTable(data,head);
content.add(new JScrollPane(jt), BorderLayout.CENTER);
jt.setDefaultRenderer(Object.class,
new MyCellRenderer(new ImageIcon("C:\\duke\\t1.gif")));
setSize(200, 200);
show();
public static void main(String args[]) { new Test(); }
class MyCellRenderer extends JLabel implements TableCellRenderer {
Icon icon;
public MyCellRenderer(Icon icon) { this.icon = icon; }
public Component getTableCellRendererComponent(
JTable table, Object color,
boolean isSelected, boolean hasFocus,
int row, int column) {
if ((row+column)%3==0) setIcon(null);
else setIcon(icon);
return this;
} -
How do I change the colour of text in a cell in a JTable?
I am trying to change the color of the text in a single cell in a JTable. I have tried not adding a cell renderer and it changes the colour of text in all cells.
I have tried adding a cell renderer to the table and it does the same ie all cells text colour changes.
I am able to add a cell renderer to a column and it changes all the cells in the column.
I cannot figure out how to change just one single cell's text colour without effecting the other cells.Ok, so if i create my own cell renderer do I set it as the default renderer for the whole table i.e.
table.setDefaultRenderer(MyCellRenderer, renderer);
Does this set one cell renderer for the whole table or is there an individual one for each cell? -
How can i change backgroup Color of a Row in JTable
Hi,
i want to change the backgroup color of a particular row in a JTable,
How can i do it??
i tried so far
table.setDefaultRenderer(Integer.class,new DefaultTableCellRenderer(){
private Color color1 = new Color(255,255,204);
private Color color2 = Color.RED;
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if( row%2 == 0 ){
c.setBackground(color1);
else{
c.setBackground(color2);
return c;
);and also i tried
TableCellRenderer renderer=null;
renderer = table.getCellRenderer(i,0);
Component component = renderer.getTableCellRendererComponent(table,"",true,true,i,0);
if(item.getItemStatus().equals("Open")){
component.setBackground(java.awt.Color.LIGHT_GRAY);
else if(item.getItemStatus().equals("Buy It Now")){
component.setBackground(java.awt.Color.YELLOW);
else {
component.setBackground(java.awt.Color.RED);
}the 2nd code change the background color of whole table, while the 1st one doing nothing. please help me.......Try setting the cell renderer this way:
DefaultTableCellRenderer cellRenderer = new DefaultTableCellRenderer() {
private Color color1 = new Color(255,255,204);
private Color color2 = Color.RED;
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
System.out.println("test");
Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if( row%2 == 0 ){
c.setBackground(color1);
else{
c.setBackground(color2);
return c;
for (int i = 0; i < table.getColumnCount(); i++)
table.getColumnModel().getColumn(i).setCellRenderer(cellRenderer); -
JTable problem...can anybody help me...
hi i have try out some jtable program. I have done some alteration to the table that it can resize row and column via the gridline. but it seems that when i'm resizing through the gridline, the row header did not resize. I sense that the row header not syncronizing with the main table. So when i'm tried to resize, the row header didn't
can you solve my problem...
//the main program
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
public class Test { public static void main(String[] args)
//row headers:
String[][] rowHeaders = {{"Alpha"},{"Beta"}, {"Gamma"}};
JTable leftTable = new JTable(rowHeaders, new Object[]{""});
leftTable.setDefaultRenderer(
Object.class, leftTable.getTableHeader().getDefaultRenderer());
leftTable.setPreferredScrollableViewportSize(new Dimension(50,100));
//main table:
Object[][] sampleData = {{"Homer", "Simpson"},{"Seymour","Skinner"},{"Ned","Flanders"}};
JTable mainTable = new JTable(sampleData, new Object[]{"",""});
//scroll pane:
JScrollPane sp = new JScrollPane(
mainTable, ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
sp.setRowHeaderView(leftTable);
sp.setColumnHeaderView(null);
new TableColumnResizer(mainTable);
new TableRowResizer(mainTable);
//frame:
final JFrame f = new JFrame("Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(sp);
f.pack();
SwingUtilities.invokeLater(new Runnable(){
public void run(){ f.setLocationRelativeTo(null);
f.setVisible(true); } });
}This the TableColumnResizer.java
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.event.MouseInputAdapter;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.*;
public class TableColumnResizer extends MouseInputAdapter
public static Cursor resizeCursor = Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR);
private int mouseXOffset;
private Cursor otherCursor = resizeCursor;
private JTable table;
public TableColumnResizer(JTable table){
this.table = table;
table.addMouseListener(this);
table.addMouseMotionListener(this);
private boolean canResize(TableColumn column){
return column != null
&& table.getTableHeader().getResizingAllowed()
&& column.getResizable();
private TableColumn getResizingColumn(Point p){
return getResizingColumn(p, table.columnAtPoint(p));
private TableColumn getResizingColumn(Point p, int column){
if(column == -1){
return null;
int row = table.rowAtPoint(p);
if(row==-1)
return null;
Rectangle r = table.getCellRect(row, column, true);
r.grow( -3, 0);
if(r.contains(p))
return null;
int midPoint = r.x + r.width / 2;
int columnIndex;
if(table.getTableHeader().getComponentOrientation().isLeftToRight())
columnIndex = (p.x < midPoint) ? column - 1 : column;
else
columnIndex = (p.x < midPoint) ? column : column - 1;
if(columnIndex == -1)
return null;
return table.getTableHeader().getColumnModel().getColumn(columnIndex);
public void mousePressed(MouseEvent e){
table.getTableHeader().setDraggedColumn(null);
table.getTableHeader().setResizingColumn(null);
table.getTableHeader().setDraggedDistance(0);
Point p = e.getPoint();
// First find which header cell was hit
int index = table.columnAtPoint(p);
if(index==-1)
return;
// The last 3 pixels + 3 pixels of next column are for resizing
TableColumn resizingColumn = getResizingColumn(p, index);
if(!canResize(resizingColumn))
return;
table.getTableHeader().setResizingColumn(resizingColumn);
if(table.getTableHeader().getComponentOrientation().isLeftToRight())
mouseXOffset = p.x - resizingColumn.getWidth();
else
mouseXOffset = p.x + resizingColumn.getWidth();
private void swapCursor(){
Cursor tmp = table.getCursor();
table.setCursor(otherCursor);
otherCursor = tmp;
public void mouseMoved(MouseEvent e){
if(canResize(getResizingColumn(e.getPoint()))
!= (table.getCursor() == resizeCursor)){
swapCursor();
public void mouseDragged(MouseEvent e){
int mouseX = e.getX();
TableColumn resizingColumn = table.getTableHeader().getResizingColumn();
boolean headerLeftToRight =
table.getTableHeader().getComponentOrientation().isLeftToRight();
if(resizingColumn != null){
int oldWidth = resizingColumn.getWidth();
int newWidth;
if(headerLeftToRight){
newWidth = mouseX - mouseXOffset;
} else{
newWidth = mouseXOffset - mouseX;
resizingColumn.setWidth(newWidth);
Container container;
if((table.getTableHeader().getParent() == null)
|| ((container = table.getTableHeader().getParent().getParent()) == null)
|| !(container instanceof JScrollPane)){
return;
if(!container.getComponentOrientation().isLeftToRight()
&& !headerLeftToRight){
if(table != null){
JViewport viewport = ((JScrollPane)container).getViewport();
int viewportWidth = viewport.getWidth();
int diff = newWidth - oldWidth;
int newHeaderWidth = table.getWidth() + diff;
/* Resize a table */
Dimension tableSize = table.getSize();
tableSize.width += diff;
table.setSize(tableSize);
* If this table is in AUTO_RESIZE_OFF mode and has a horizontal
* scrollbar, we need to update a view's position.
if((newHeaderWidth >= viewportWidth)
&& (table.getAutoResizeMode() == JTable.AUTO_RESIZE_OFF)){
Point p = viewport.getViewPosition();
p.x =
Math.max(0, Math.min(newHeaderWidth - viewportWidth, p.x + diff));
viewport.setViewPosition(p);
/* Update the original X offset value. */
mouseXOffset += diff;
public void mouseReleased(MouseEvent e){
table.getTableHeader().setResizingColumn(null);
table.getTableHeader().setDraggedColumn(null);
} This is TableRowResizer.java
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.event.MouseInputAdapter;
import java.awt.*;
import java.awt.event.MouseEvent;
public class TableRowResizer extends MouseInputAdapter
public static Cursor resizeCursor = Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR);
private int mouseYOffset, resizingRow;
private Cursor otherCursor = resizeCursor;
private JTable table;
public TableRowResizer(JTable table){
this.table = table;
table.addMouseListener(this);
table.addMouseMotionListener(this);
private int getResizingRow(Point p){
return getResizingRow(p, table.rowAtPoint(p));
private int getResizingRow(Point p, int row){
if(row == -1){
return -1;
int col = table.columnAtPoint(p);
if(col==-1)
return -1;
Rectangle r = table.getCellRect(row, col, true);
r.grow(0, -3);
if(r.contains(p))
return -1;
int midPoint = r.y + r.height / 2;
int rowIndex = (p.y < midPoint) ? row - 1 : row;
return rowIndex;
public void mousePressed(MouseEvent e){
Point p = e.getPoint();
resizingRow = getResizingRow(p);
mouseYOffset = p.y - table.getRowHeight(resizingRow);
private void swapCursor(){
Cursor tmp = table.getCursor();
table.setCursor(otherCursor);
otherCursor = tmp;
public void mouseMoved(MouseEvent e){
if((getResizingRow(e.getPoint())>=0)
!= (table.getCursor() == resizeCursor)){
swapCursor();
public void mouseDragged(MouseEvent e){
int mouseY = e.getY();
if(resizingRow >= 0){
int newHeight = mouseY - mouseYOffset;
if(newHeight > 0)
table.setRowHeight(resizingRow, newHeight);
}cross-post: http://forum.java.sun.com/thread.jspa?forumID=57&threadID=755250
-
JTable displays string in wrong order : my code problem or Java problem ?
I have the following code that displays data in a JTable, most of the time it works fine, but I've realized when I have a cell with values like : "Snowboarding"+"[123456789]"
It would display it as : [Snowboarding[123456789
For a string like : "Chasing toddlers"+"<123456789>"
It would display it as : <Chasing toddlers<123456789
It not only moved the last bracket to the front, but also changed its direction from "]" to "[" and from ">" to "<"
Is there anything wrong with my code ? Or is this a Java problem ?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import java.io.*;
import java.sql.*;
import java.util.*;
import java.util.List;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
public class Table_Panel extends JPanel implements ItemListener
public static final long serialVersionUID=26362862L;
static final int Row_Color_Style_Default=-1,Row_Color_Style_None=0,Row_Color_Style_Blue_Gray=1,Row_Color_Style_Cyan_Gray=2,Row_Color_Style_Blue=3,
Row_Color_Style_Gray=4,Row_Color_Style_Red_Green=5,Row_Color_Style_Green_Yellow=6,Row_Color_Style_Red_Yellow=7,
Max_Header_Cell_Width=0,Header_Width=1,Cell_Width=2;
static int Row_Color_Style=Row_Color_Style_Cyan_Gray,Preffered_Width=Header_Width;
// static int Row_Color_Style=Row_Color_Style_None,Preffered_Width=Header_Width;
//boolean Debug=true,
boolean Debug=false,
// Use_Row_Colors=true,
Use_Row_Colors=false;
JFrame Table_Frame;
TableModel My_Model;
JScrollPane scrollPane=new JScrollPane();
public JTable Table;
static String columnNames[],Default_Delimiter=\",\";
Object[][] data;
static Dimension Screen_Size=Toolkit.getDefaultToolkit().getScreenSize();
int Column_Width[];
static Color Default_Selection_Color=new Color(250,135,200);
Color Selection_Color=Default_Selection_Color;
public Table_Panel(ResultSet RS,String Table_Name,boolean Show_External_Table,int Row_Color_Style,int Preffered_Width,boolean In_Original_Order)
String Value,Table_Column_Names[]=null;
Object[][] Table_Data=null;
int Row_Count,Index=0;
try
if (RS==null) return;
else
RS.last();
Row_Count=RS.getRow();
RS.beforeFirst();
ResultSetMetaData rsmd=RS.getMetaData();
int Column_Count=rsmd.getColumnCount();
Table_Column_Names=new String[Column_Count];
Table_Data=new Object[Row_Count][Column_Count];
for (int i=1;i<=Column_Count;i++) Table_Column_Names[i-1]=rsmd.getColumnLabel(i); // Get column names
//Out("Row_Count="+Row_Count+" Column_Count="+Column_Count);
while (RS.next()) // Get all rows
for (int i=1;i<=Column_Count;i++)
Value=RS.getString(i);
Table_Data[Index][i-1]=(Value==null)?"null":Value;
Index++;
// if (Test_Ct++>300) break;
catch (Exception e) { e.printStackTrace(); }
scrollPane=new Table_Panel(Table_Name,Table_Column_Names,Table_Data,Table_Data.length,false,Show_External_Table,false,Row_Color_Style,Preffered_Width,Selection_Color,In_Original_Order).scrollPane;
public Table_Panel(String[] Table_Column_Names,Object[][] Table_Data,Color Selection_Color,boolean In_Original_Order)
this("",Table_Column_Names,Table_Data,Table_Data.length,false,false,false,Row_Color_Style,Preffered_Width,Selection_Color,In_Original_Order);
public Table_Panel(String Table_Name,String[] Table_Column_Names,Object[][] Table_Data,boolean Show_External_Table,Color Selection_Color,boolean In_Original_Order)
this(Table_Name,Table_Column_Names,Table_Data,Table_Data.length,false,Show_External_Table,false,Row_Color_Style,Preffered_Width,Selection_Color,In_Original_Order);
public Table_Panel(String Table_Name,String[] Table_Column_Names,Object[][] Table_Data,int Row_Count,boolean Is_Child,boolean Show_External_Table,boolean Manage_Attachment,int Row_Color_Style,int Preffered_Width,Color Selection_Color,boolean In_Original_Order)
columnNames=Table_Column_Names;
if (In_Original_Order) data=Table_Data;
else
data=new Object[Table_Data.length][columnNames.length];
for (int row=0;row<Table_Data.length;row++)
data[row]=new Object[columnNames.length];
for (int Column=0;Column<Table_Data[row].length;Column++) data[row][Column]=Table_Data[Table_Data.length-1-row][Column];
Column_Width=new int[columnNames.length];
this.Row_Color_Style=Row_Color_Style;
Use_Row_Colors=(Row_Color_Style!=Row_Color_Style_None);
this.Preffered_Width=Preffered_Width;
if (Selection_Color!=null) this.Selection_Color=Selection_Color;
// Out("this.Selection_Color="+this.Selection_Color);
// TableModel My_Model=new DefaultTableModel(Table_Data,columnNames)
TableModel My_Model=new DefaultTableModel(data,columnNames)
public int getColumnCount() { return columnNames.length; }
public int getRowCount() { return data.length; }
public String getColumnName(int col) { return columnNames[col]; }
public Object getValueAt(int row,int col)
// Out(row+","+col+"["+data[row][col]+"] data.length="+data.length+" data[0].length="+data[0].length);
return (data[row][col]==null)?"":((data[row][col] instanceof Boolean)?data[row][col]:data[row][col].toString()); // Non-boolean values will have bgcolor
public Class getColumnClass(int column)
Class returnValue;
if ((column>=0) && (column<getColumnCount())) returnValue=getValueAt(0,column).getClass();
else returnValue=Object.class;
return returnValue;
// JTable uses this method to determine the default renderer/editor for each cell. If we didn't implement this method, then the last column would contain text ("true"/"false"), rather than a check box.
// public Class getColumnClass(int c) { return getValueAt(0,c).getClass(); }
// Don't need to implement this method unless your table's editable.
public boolean isCellEditable(int row,int col)
//Note that the data/cell address is constant, no matter where the cell appears onscreen.
if (col<0) return false;
else return true;
// Don't need to implement this method unless your table's data can change.
public void setValueAt(Object value,int row,int col)
String Execution_Dir=getClass().getProtectionDomain().getCodeSource().getLocation().toString();
if (Debug) System.out.println("Execution_Dir="+Execution_Dir+"\nLast_Value="+Table_Grid_Cell_Renderer.Last_Value+" Setting value at [ "+row+","+col+" ] to "+value+" (an instance of "+value.getClass()+")");
if (Execution_Dir.toLowerCase().indexOf("c:/")!=-1 || value.getClass()==Boolean.class || !Use_Row_Colors) data[row][col]=value;
// else data[row][col]=(Table_Grid_CellRenderer.Last_Value==null)?value:value.toString().substring(Table_Grid_CellRenderer.Last_Value.toString().length());
fireTableCellUpdated(row,col);
if (Debug)
System.out.println("New value of data :");
printDebugData();
private void printDebugData()
int numRows=getRowCount();
int numCols=getColumnCount();
for (int i=0;i<numRows;i++)
System.out.print(" row "+i+":");
for (int j=0;j<numCols;j++) System.out.print(" "+data[i][j]);
System.out.println();
System.out.println("--------------------------------------------------------------------------");
TableSorter sorter=new TableSorter(My_Model);
Table=new JTable(sorter)
// Table=new JTable(My_Model)
public static final long serialVersionUID=26362862L;
public String getToolTipText(MouseEvent e) // Implement table cell tool tips.
Object Cell_Tip;
String tip=null;
java.awt.Point p=e.getPoint();
int rowIndex=rowAtPoint(p);
int colIndex=columnAtPoint(p);
int realColumnIndex=convertColumnIndexToModel(colIndex);
Cell_Tip=getValueAt(rowIndex,colIndex);
// if (realColumnIndex == 2) //Sport column
tip=Cell_Tip.toString();
else if (realColumnIndex == 4) //Veggie column
TableModel model=getModel();
String firstName=(String)model.getValueAt(rowIndex,0);
String lastName=(String)model.getValueAt(rowIndex,1);
Boolean veggie=(Boolean)model.getValueAt(rowIndex,4);
if (Boolean.TRUE.equals(veggie)) tip=firstName+" "+lastName+" is a vegetarian";
else tip=firstName+" "+lastName+" is not a vegetarian";
else
// You can omit this part if you know you don't have any renderers that supply their own tool tips.
tip=super.getToolTipText(e);
return tip;
// RowSorter<TableModel> sorter=new TableRowSorter<TableModel>(My_Model);
// Table.setRowSorter(sorter);
Table.setSelectionBackground(this.Selection_Color);
int Table_Height=Table.getRowHeight()*Row_Count;
// sorter.addMouseListenerToHeaderInTable(Table); // ADDED THIS
sorter.setTableHeader(Table.getTableHeader());
if (Table_Column_Names.length>20) Table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
if (Manage_Attachment) Table.setPreferredScrollableViewportSize(new Dimension(500,(Table_Height>850)?850:Table_Height));
else Table.setPreferredScrollableViewportSize(new Dimension(1000,(Table_Height>850)?850:Table_Height));
if (Use_Row_Colors) Table.setDefaultRenderer(Object.class,new Table_Grid_Cell_Renderer());
//Create the scroll pane and add the table to it.
scrollPane=new JScrollPane(Table);
//Set up column sizes.
initColumnSizes(Table,My_Model);
//Add the scroll pane to this window.
if (Show_External_Table)
Table_Frame=new JFrame(Table_Name);
Table_Frame.getContentPane().add(scrollPane);
Table_Frame.addWindowListener(new WindowAdapter()
public void windowActivated(WindowEvent e) { }
public void windowClosed(WindowEvent e) { }
public void windowClosing(WindowEvent e) { System.exit(0); }
public void windowDeactivated(WindowEvent e) { }
public void windowDeiconified(WindowEvent e) { scrollPane.repaint(); }
public void windowGainedFocus(WindowEvent e) { scrollPane.repaint(); }
public void windowIconified(WindowEvent e) { }
public void windowLostFocus(WindowEvent e) { }
public void windowOpening(WindowEvent e) { scrollPane.repaint(); }
public void windowOpened(WindowEvent e) { }
public void windowResized(WindowEvent e) { scrollPane.repaint(); }
public void windowStateChanged(WindowEvent e) { scrollPane.repaint(); }
Table_Frame.pack();
Table_Frame.setBounds((Screen_Size.width-Table_Frame.getWidth())/2,(Screen_Size.height-Table_Frame.getHeight())/2,Table_Frame.getWidth(),Table_Frame.getHeight());
Table_Frame.setVisible(true);
if (Is_Child) Table_Frame.addComponentListener(new ComponentAdapter() { public void componentClosing(ComponentEvent e) { System.exit(0); } });
else add(scrollPane);
public Table_Panel(String File_Name) { this(File_Name,false,Row_Color_Style_Cyan_Gray,Preffered_Width,null,Default_Selection_Color,true); }
public Table_Panel(String File_Name,int Row_Color_Style,boolean In_Original_Order) { this(File_Name,false,Row_Color_Style,Preffered_Width,null,Default_Selection_Color,In_Original_Order); }
public Table_Panel(String File_Name,String Delimiter,boolean In_Original_Order) { this(File_Name,false,Row_Color_Style_Cyan_Gray,Preffered_Width,Delimiter,Default_Selection_Color,In_Original_Order); }
public Table_Panel(String File_Name,int Preffered_Width,String Delimiter,boolean In_Original_Order) { this(File_Name,false,Row_Color_Style,Preffered_Width,Delimiter,Default_Selection_Color,In_Original_Order); }
public Table_Panel(String File_Name,int Row_Color_Style,int Preffered_Width,String Delimiter,boolean In_Original_Order) { this(File_Name,false,Row_Color_Style,Preffered_Width,Delimiter,Default_Selection_Color,In_Original_Order); }
public Table_Panel(String File_Name,boolean Show_External_Table,boolean In_Original_Order) { this(File_Name,Show_External_Table,Row_Color_Style,Preffered_Width,null,Default_Selection_Color,In_Original_Order); }
public Table_Panel(String File_Name,boolean Show_External_Table,String Delimiter,boolean In_Original_Order) { this(File_Name,Show_External_Table,Row_Color_Style,Preffered_Width,Delimiter,Default_Selection_Color,In_Original_Order); }
public Table_Panel(String File_Name,boolean Show_External_Table,int Row_Color_Style,int Preffered_Width,String Delimiter,Color Selection_Color,boolean In_Original_Order)
String Table_Column_Names[],Column_Name_Line="";
int Row_Count=0,Index=0;
boolean Is_Child=false,Manage_Attachment=false;
StringTokenizer ST;
if (Delimiter==null) Delimiter=Default_Delimiter;
if (new File(File_Name).exists())
try
String Line,Str=Tool_Lib.Read_File(File_Name).toString();
ST=new StringTokenizer(Str,"\n");
Line=ST.nextToken();
Row_Count=ST.countTokens();
Object[][] Table_Data=new Object[Row_Count][];
if (Delimiter.equals(" ")) Line=Line.replaceAll(" {2,}"," ").trim(); // Replace multiple spaces with the delimiter space
Table_Column_Names=Line.split(Delimiter);
columnNames=Table_Column_Names;
for (int i=0;i<Table_Column_Names.length;i++) Column_Name_Line+=Table_Column_Names[i]+" ";
//Out("Column_Name_Line [ "+Table_Column_Names.length+" ]="+Column_Name_Line);
while (ST.hasMoreTokens())
Line=ST.nextToken();
//Out(Line);
if (Delimiter.equals(" ")) Line=Line.replaceAll(" {2,}"," ").trim(); // Replace multiple spaces with the delimiter space
if (Line.indexOf(Delimiter)!=-1) Table_Data[Index]=Line.split(Delimiter);
else
Table_Data[Index]=new Object[Table_Column_Names.length];
Table_Data[Index][0]=Line;
for (int i=1;i<Table_Column_Names.length;i++) Table_Data[Index]="";
Index++;
Line="";
for (int i=0;i<Table_Data.length;i++)
Line+="[ "+Table_Data[i].length+" ] ";
for (int j=0;j<Table_Data[i].length;j++) Line+=Table_Data[i][j]+" ";
Line+="\n";
Out(Line);
Table_Panel A_Table_Panel=new Table_Panel(File_Name,Table_Column_Names,Table_Data,Row_Count,Is_Child,Show_External_Table,Manage_Attachment,Row_Color_Style,Preffered_Width,Selection_Color,In_Original_Order);
Table=A_Table_Panel.Table;
scrollPane=A_Table_Panel.scrollPane;
Column_Width=A_Table_Panel.Column_Width;
data=A_Table_Panel.data;
catch (Exception e) { e.printStackTrace(); }
public void setPreferredSize(Dimension A_Dimension) { scrollPane.setPreferredSize(A_Dimension); }
// This method picks good column sizes. If all column heads are wider than the column's cells' contents, then you can just use column.sizeWidthToFit().
void initColumnSizes(JTable table,TableModel model)
TableColumn column=null;
Component comp=null;
int headerWidth=0,cellWidth=0;
Object[] longValues=(data.length>0)?data[0]:null;
TableCellRenderer headerRenderer=table.getTableHeader().getDefaultRenderer();
if (data.length<1) return;
for (int i=0;i<model.getColumnCount();i++)
column=table.getColumnModel().getColumn(i);
comp=headerRenderer.getTableCellRendererComponent(null,column.getHeaderValue(),false,false,0,0);
headerWidth=comp.getPreferredSize().width;
comp=table.getDefaultRenderer(model.getColumnClass(i)).
getTableCellRendererComponent(table,longValues[i],false,false,0,i);
cellWidth=comp.getPreferredSize().width;
switch (Preffered_Width)
case Max_Header_Cell_Width : column.setPreferredWidth(Math.max(headerWidth,cellWidth));break;
case Header_Width : column.setPreferredWidth(headerWidth);break;
case Cell_Width : column.setPreferredWidth(cellWidth);break;
Column_Width[i]=column.getPreferredWidth();
if (Debug) Out("Initializing width of column "+i+". "+"headerWidth="+headerWidth+"; cellWidth="+cellWidth+" Column_Width["+i+"]="+Column_Width[i]);
// Detects a state change in any of the Lists. Resets the variable corresponding to the selected item in a particular List. Invokes changeFont with the currently selected fontname, style and size attributes.
public void itemStateChanged(ItemEvent e)
Out(e.toString());
if (e.getStateChange() != ItemEvent.SELECTED) return;
Object list=e.getSource();
public static void Out(String message) { System.out.println(message); }
// Create the GUI and show it. For thread safety, this method should be invoked from the event-dispatching thread.
static void Create_And_Show_GUI()
boolean Demo_External_Table=true;
// boolean Demo_External_Table=false;
final Table_Panel demo;
String[] columnNames={"First Names","Last Names","Sport","Num of Years","Vegetarian"};
Object[][] data={{"Mary","Campione","Snowboarding"+"[123456789]",new Integer(5),new Boolean(false)},
{"Alison","Huml","Rowing"+":123456789]",new Integer(3),new Boolean(true)},
{"Frank","Ni","Running"+":123456789", new Integer(12), new Boolean(false)},
{"Kathy","Walrath","Chasing toddlers"+"<123456789>", new Integer(2), new Boolean(false)},
{"Mark", "Andrews","Speed reading",new Integer(20),new Boolean(true)},
{"Angela","Lih","Teaching high school",new Integer(36),new Boolean(false)} };
// Row_Color_Style=Row_Color_Style_Default;
// Row_Color_Style=Row_Color_Style_None;
// Row_Color_Style=Row_Color_Style_Blue_Gray;
Row_Color_Style=Row_Color_Style_Cyan_Gray;
// Row_Color_Style=Row_Color_Style_Blue;
// Row_Color_Style=Row_Color_Style_Gray;
// Row_Color_Style=Row_Color_Style_Red_Green;
// Row_Color_Style=Row_Color_Style_Green_Yellow;
// Row_Color_Style=Row_Color_Style_Red_Yellow;
Preffered_Width=Max_Header_Cell_Width;
if (Demo_External_Table) demo=new Table_Panel("External Table Demo",columnNames,data,data.length,false,Demo_External_Table,false,Row_Color_Style,Max_Header_Cell_Width,Default_Selection_Color,true);
else
JFrame Table_Frame=new JFrame("Internal Table Demo");
// demo=new Table_Panel(Nm_Lib.Dir_A_Test+"ELX.csv",false,Row_Color_Style,Preffered_Width,null);
// demo=new Table_Panel(Nm_Lib.Dir_Stock_Data+"ABV_Data.txt",false,Row_Color_Style,Preffered_Width," ");
demo=new Table_Panel("C:/Dir_Stock_Data/EOP.txt",",",false);
// demo=new Table_Panel(Nm_Lib.Dir_Stock_Data+"ABV_Data.txt"," ",false);
Table_Frame.getContentPane().add(demo.scrollPane);
Table_Frame.addWindowListener(new WindowAdapter()
public void windowActivated(WindowEvent e) { }
public void windowClosed(WindowEvent e) { }
public void windowClosing(WindowEvent e) { System.exit(0); }
public void windowDeactivated(WindowEvent e) { }
public void windowDeiconified(WindowEvent e) { demo.repaint(); }
public void windowGainedFocus(WindowEvent e) { demo.repaint(); }
public void windowIconified(WindowEvent e) { }
public void windowLostFocus(WindowEvent e) { }
public void windowOpening(WindowEvent e) { demo.repaint(); }
public void windowOpened(WindowEvent e) { }
public void windowResized(WindowEvent e) { demo.repaint(); }
public void windowStateChanged(WindowEvent e) { demo.repaint(); }
Table_Frame.pack();
Table_Frame.setBounds((Screen_Size.width-Table_Frame.getWidth())/2,(Screen_Size.height-Table_Frame.getHeight())/2,Table_Frame.getWidth(),Table_Frame.getHeight());
Table_Frame.setVisible(true);
public static void main(String[] args)
// Schedule a job for the event-dispatching thread : creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() { public void run() { Create_And_Show_GUI(); } });
* TableSorter is a decorator for TableModels; adding sorting functionality to a supplied TableModel. TableSorter does not store
* or copy the data in its TableModel; instead it maintains a map from the row indexes of the view to the row indexes of the
* model. As requests are made of the sorter (like getValueAt(row, col)) they are passed to the underlying model after the row numbers
* have been translated via the internal mapping array. This way, the TableSorter appears to hold another copy of the table
* with the rows in a different order.
* <p/>
* TableSorter registers itself as a listener to the underlying model, just as the JTable itself would. Events recieved from the model
* are examined, sometimes manipulated (typically widened), and then passed on to the TableSorter's listeners (typically the JTable).
* If a change to the model has invalidated the order of TableSorter's rows, a note of this is made and the sorter will resort the
* rows the next time a value is requested.
* <p/>
* When the tableHeader property is set, either by using the setTableHeader() method or the two argument constructor, the table
* header may be used as a complete UI for TableSorter. The default renderer of the tableHeader is decorated with a renderer
* that indicates the sorting status of each column. In addition, a mouse listener is installed with the following behavior:
* <ul>
* <li>
* Mouse-click: Clears the sorting status of all other columns and advances the sorting status of that column through three
* values: {NOT_SORTED, ASCENDING, DESCENDING} (then back to NOT_SORTED again).
* <li>
* SHIFT-mouse-click: Clears the sorting status of all other columns and cycles the sorting status of the column through the same
* three values, in the opposite order: {NOT_SORTED, DESCENDING, ASCENDING}.
* <li>
* CONTROL-mouse-click and CONTROL-SHIFT-mouse-click: as above except that the changes to the column do not cancel the statuses of columns
* that are already sorting - giving a way to initiate a compound sort.
* </ul>
* <p/>
* This is a long overdue rewrite of a class of the same name that first appeared in the swing table demos in 1997.
* @author Philip Milne
* @author Brendon McLean
* @author Dan van Enckevort
* @author Parwinder Sekhon
* @version 2.0 02/27/04
class TableSorter extends AbstractTableModel
public static final long serialVersionUID=26362862L;
protected TableModel tableModel;
public static final int DESCENDING = -1;
public static final int NOT_SORTED = 0;
public static final int ASCENDING = 1;
private static Directive EMPTY_DIRECTIVE = new Directive(-1, NOT_SORTED);
public static final Comparator COMPARABLE_COMAPRATOR = new Comparator() { public int compare(Object o1, Object o2) { return ((Comparable) o1).compareTo(o2); } };
public static final Comparator LEXICAL_COMPARATOR = new Comparator() { public int compare(Object o1, Object o2) { return o1.toString().compareTo(o2.toString()); } };
private Row[] viewToModel;
private int[] modelToView;
private JTableHeader tableHeader;
private MouseListener mouseListener;
private TableModelListener tableModelListener;
private Map<Class,Comparator> columnComparators = new HashMap<Class,Comparator>();
private List<Directive> sortingColumns = new ArrayList<Directive>();
public TableSorter()
this.mouseListener = new MouseHandler();
this.tableModelListener = new TableModelHandler();
public TableSorter(TableModel tableModel)
this();
setTableModel(tableModel);
public TableSorter(TableModel tableModel, JTableHeader tableHeader)
this();
setTableHeader(tableHeader);
setTableModel(tableModel);
private void clearSortingState()
viewToModel = null;
modelToView = null;
public TableModel getTableModel() { return tableModel; }
public void setTableModel(TableModel tableModel)
if (this.tableModel != null) { this.tableModel.removeTableModelListener(tableModelListener); }
this.tableModel = tableModel;
if (this.tableModel != null) { this.tableModel.addTableModelListener(tableModelListener); }
clearSortingState();
fireTableStructureChanged();
public JTableHeader getTableHeader() { return tableHeader; }
public void setTableHeader(JTableHeader tableHeader)
if (this.tableHeader != null)
this.tableHeader.removeMouseListener(mouseListener);
TableCellRenderer defaultRenderer = this.tableHeader.getDefaultRenderer();
if (defaultRenderer instanceof SortableHeaderRenderer) this.tableHeader.setDefaultRenderer(((SortableHeaderRenderer) defaultRenderer).tableCellRenderer);
this.tableHeader = tableHeader;
if (this.tableHeader != null)
this.tableHeader.addMouseListener(mouseListener);
this.tableHeader.setDefaultRenderer(
new SortableHeaderRenderer(this.tableHeader.getDefaultRenderer()));
public boolean isSorting() { return sortingColumns.size() != 0; }
private Directive getDirective(int column)
for (int i = 0; i < sortingColumns.size(); i++)
Directive directive = (Directive)sortingColumns.get(i);
if (directive.column == column) { return directive; }
return EMPTY_DIRECTIVE;
public int getSortingStatus(int column) { return getDirective(column).direction; }
private void sortingStatusChanged()
clearSortingState();
fireTableDataChanged();
if (tableHeader != null) { tableHeader.repaint(); }
public void setSortingStatus(int column, int status)
Directive directive = getDirective(column);
if (directive != EMPTY_DIRECTIVE) { sortingColumns.remove(directive); }
if (status != NOT_SORTED) { sortingColumns.add(new Directive(column, status)); }
sortingStatusChanged();
protected Icon getHeaderRendererIcon(int column, int size)
Directive directive = getDirective(column);
if (directive == EMPTY_DIRECTIVE) { return null; }
return new Arrow(directive.direction == DESCENDING, size, sortingColumns.indexOf(directive));
private void cancelSorting()
sortingColumns.clear();
sortingStatusChanged();
public void setColumnComparator(Class type, Comparator comparator)
if (comparator == null) { columnComparators.remove(type); }
else { columnComparators.put(type, comparator); }
protected Comparator getComparator(int column)
Class columnType = tableModel.getColumnClass(column);
Comparator comparator = (Comparator) columnComparators.get(columnType);
if (comparator != null) { return comparator; }
if (Comparable.class.isAssignableFrom(columnType)) { return COMPARABLE_COMAPRATOR; }
return LEXICAL_COMPARATOR;
private Row[] getViewToModel()
if (viewToModel == null)
int tableModelRowCount = tableModel.getRowCount();
viewToModel = new Row[tableModelRowCount];
for (int row = 0; row < tableModelRowCount; row++) { viewToModel[row] = new Row(row); }
if (isSorting()) { Arrays.sort(viewToModel); }
return viewToModel;
public int modelIndex(int viewIndex) { return getViewToModel()[viewIndex].modelIndex; }
private int[] getModelToView()
if (modelToView == null)
int n = getViewToModel().length;
modelToView = new int[n];
for (int i = 0; i < n; i++) { modelToView[modelIndex(i)] = i; }
return modelToView;
// TableModel interface methods
public int getRowCount() { return (tableModel == null) ? 0 : tableModel.getRowCount(); }
public int getColumnCount() { return (tableModel == null) ? 0 : tableModel.getColumnCount(); }
public String getColumnName(int column) { return tableModel.getColumnName(column); }
public Class getColumnClass(int column) { return tableModel.getColumnClass(column); }
public boolean isCellEditable(int row, int column) { return tableModel.isCellEditable(modelIndex(row), column); }
public Object getValueAt(int row, int column) { return tableModel.getValueAt(modelIndex(row), column); }
public void setValueAt(Object aValue, int row, int column) { tableModel.setValueAt(aValue, modelIndex(row), column); }
// Helper classes
private class Row implements Comparable
private int modelIndex;
public Row(int index) { this.modelIndex = index; }
public int compareTo(Object o)
int row1 = modelIndex;
int row2 = ((Row) o).modelIndex;
for (Iterator it = sortingColumns.iterator(); it.hasNext();)
Directive directive = (Directive) it.next();
int column = directive.column;
Object o1 = tableModel.getValueAt(row1, column);
Object o2 = tableModel.getValueAt(row2, column);
int comparison = 0;
// Define null less than everything, except null.import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import java.io.*;
import java.sql.*;
import java.util.*;
import java.util.List;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
public class Table_Panel extends JPanel implements ItemListener
public static final long serialVersionUID=26362862L;
static final int Row_Color_Style_Default=-1,Row_Color_Style_None=0,Row_Color_Style_Blue_Gray=1,Row_Color_Style_Cyan_Gray=2,Row_Color_Style_Blue=3,
Row_Color_Style_Gray=4,Row_Color_Style_Red_Green=5,Row_Color_Style_Green_Yellow=6,Row_Color_Style_Red_Yellow=7,
Max_Header_Cell_Width=0,Header_Width=1,Cell_Width=2;
static int Row_Color_Style=Row_Color_Style_Cyan_Gray,Preffered_Width=Header_Width;
// static int Row_Color_Style=Row_Color_Style_None,Preffered_Width=Header_Width;
//boolean Debug=true,
boolean Debug=false,
// Use_Row_Colors=true,
Use_Row_Colors=false;
JFrame Table_Frame;
TableModel My_Model;
JScrollPane scrollPane=new JScrollPane();
public JTable Table;
static String columnNames[],Default_Delimiter=",";
Object[][] data;
static Dimension Screen_Size=Toolkit.getDefaultToolkit().getScreenSize();
int Column_Width[];
static Color Default_Selection_Color=new Color(250,135,200);
Color Selection_Color=Default_Selection_Color;
public Table_Panel(ResultSet RS,String Table_Name,boolean Show_External_Table,int Row_Color_Style,int Preffered_Width,boolean In_Original_Order)
String Value,Table_Column_Names[]=null;
Object[][] Table_Data=null;
int Row_Count,Index=0;
try
if (RS==null) return;
else
RS.last();
Row_Count=RS.getRow();
RS.beforeFirst();
ResultSetMetaData rsmd=RS.getMetaData();
int Column_Count=rsmd.getColumnCount();
Table_Column_Names=new String[Column_Count];
Table_Data=new Object[Row_Count][Column_Count];
for (int i=1;i<=Column_Count;i++) Table_Column_Names[i-1]=rsmd.getColumnLabel(i); // Get column names
//Out("Row_Count="+Row_Count+" Column_Count="+Column_Count);
while (RS.next()) // Get all rows
for (int i=1;i<=Column_Count;i++)
Value=RS.getString(i);
Table_Data[Index][i-1]=(Value==null)?"null":Value;
Index++;
// if (Test_Ct++>300) break;
catch (Exception e) { e.printStackTrace(); }
scrollPane=new Table_Panel(Table_Name,Table_Column_Names,Table_Data,Table_Data.length,false,Show_External_Table,false,Row_Color_Style,Preffered_Width,Selection_Color,In_Original_Order).scrollPane;
public Table_Panel(String[] Table_Column_Names,Object[][] Table_Data,Color Selection_Color,boolean In_Original_Order)
this("",Table_Column_Names,Table_Data,Table_Data.length,false,false,false,Row_Color_Style,Preffered_Width,Selection_Color,In_Original_Order);
public Table_Panel(String Table_Name,String[] Table_Column_Names,Object[][] Table_Data,boolean Show_External_Table,Color Selection_Color,boolean In_Original_Order)
this(Table_Name,Table_Column_Names,Table_Data,Table_Data.length,false,Show_External_Table,false,Row_Color_Style,Preffered_Width,Selection_Color,In_Original_Order);
public Table_Panel(String Table_Name,String[] Table_Column_Names,Object[][] Table_Data,int Row_Count,boolean Is_Child,boolean Show_External_Table,boolean Manage_Attachment,int Row_Color_Style,int Preffered_Width,Color Selection_Color,boolean In_Original_Order)
columnNames=Table_Column_Names;
if (In_Original_Order) data=Table_Data;
else
data=new Object[Table_Data.length][columnNames.length];
for (int row=0;row<Table_Data.length;row++)
data[row]=new Object[columnNames.length];
for (int Column=0;Column<Table_Data[row].length;Column++) data[row][Column]=Table_Data[Table_Data.length-1-row][Column];
Column_Width=new int[columnNames.length];
this.Row_Color_Style=Row_Color_Style;
Use_Row_Colors=(Row_Color_Style!=Row_Color_Style_None);
this.Preffered_Width=Preffered_Width;
if (Selection_Color!=null) this.Selection_Color=Selection_Color;
// Out("this.Selection_Color="+this.Selection_Color);
// TableModel My_Model=new DefaultTableModel(Table_Data,columnNames)
TableModel My_Model=new DefaultTableModel(data,columnNames)
public int getColumnCount() { return columnNames.length; }
public int getRowCount() { return data.length; }
public String getColumnName(int col) { return columnNames[col]; }
public Object getValueAt(int row,int col)
// Out(row+","+col+"["+data[row][col]+"] data.length="+data.length+" data[0].length="+data[0].length);
return (data[row][col]==null)?"":((data[row][col] instanceof Boolean)?data[row][col]:data[row][col].toString()); // Non-boolean values will have bgcolor
public Class getColumnClass(int column)
Class returnValue;
if ((column>=0) && (column<getColumnCount())) returnValue=getValueAt(0,column).getClass();
else returnValue=Object.class;
return returnValue;
// JTable uses this method to determine the default renderer/editor for each cell. If we didn't implement this method, then the last column would contain text ("true"/"false"), rather than a check box.
// public Class getColumnClass(int c) { return getValueAt(0,c).getClass(); }
// Don't need to implement this method unless your table's editable.
public boolean isCellEditable(int row,int col)
//Note that the data/cell address is constant, no matter where the cell appears onscreen.
if (col<0) return false;
else return true;
// Don't need to implement this method unless your table's data can change.
public void setValueAt(Object value,int row,int col)
String Execution_Dir=getClass().getProtectionDomain().getCodeSource().getLocation().toString();
if (Debug) System.out.println("Execution_Dir="+Execution_Dir+"\nLast_Value="+Table_Grid_Cell_Renderer.Last_Value+" Setting value at [ "+row+","+col+" ] to "+value+" (an instance of "+value.getClass()+")");
if (Execution_Dir.toLowerCase().indexOf("c:/")!=-1 || value.getClass()==Boolean.class || !Use_Row_Colors) data[row][col]=value;
// else data[row][col]=(Table_Grid_CellRenderer.Last_Value==null)?value:value.toString().substring(Table_Grid_CellRenderer.Last_Value.toString().length());
fireTableCellUpdated(row,col);
if (Debug)
System.out.println("New value of data :");
printDebugData();
private void printDebugData()
int numRows=getRowCount();
int numCols=getColumnCount();
for (int i=0;i<numRows;i++)
System.out.print(" row "+i+":");
for (int j=0;j<numCols;j++) System.out.print(" "+data[i][j]);
System.out.println();
System.out.println("--------------------------------------------------------------------------");
TableSorter sorter=new TableSorter(My_Model);
Table=new JTable(sorter)
// Table=new JTable(My_Model)
public static final long serialVersionUID=26362862L;
public String getToolTipText(MouseEvent e) // Implement table cell tool tips.
Object Cell_Tip;
String tip=null;
java.awt.Point p=e.getPoint();
int rowIndex=rowAtPoint(p);
int colIndex=columnAtPoint(p);
int realColumnIndex=convertColumnIndexToModel(colIndex);
Cell_Tip=getValueAt(rowIndex,colIndex);
// if (realColumnIndex == 2) //Sport column
tip=Cell_Tip.toString();
else if (realColumnIndex == 4) //Veggie column
TableModel model=getModel();
String firstName=(String)model.getValueAt(rowIndex,0);
String lastName=(String)model.getValueAt(rowIndex,1);
Boolean veggie=(Boolean)model.getValueAt(rowIndex,4);
if (Boolean.TRUE.equals(veggie)) tip=firstName+" "+lastName+" is a vegetarian";
else tip=firstName+" "+lastName+" is not a vegetarian";
else
// You can omit this part if you know you don't have any renderers that supply their own tool tips.
tip=super.getToolTipText(e);
return tip;
// RowSorter<TableModel> sorter=new TableRowSorter<TableModel>(My_Model);
// Table.setRowSorter(sorter);
Table.setSelectionBackground(this.Selection_Color);
int Table_Height=Table.getRowHeight()*Row_Count;
// sorter.addMouseListenerToHeaderInTable(Table); // ADDED THIS
sorter.setTableHeader(Table.getTableHeader());
if (Table_Column_Names.length>20) Table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
if (Manage_Attachment) Table.setPreferredScrollableViewportSize(new Dimension(500,(Table_Height>850)?850:Table_Height));
else Table.setPreferredScrollableViewportSize(new Dimension(1000,(Table_Height>850)?850:Table_Height));
if (Use_Row_Colors) Table.setDefaultRenderer(Object.class,new Table_Grid_Cell_Renderer());
//Create the scroll pane and add the table to it.
scrollPane=new JScrollPane(Table);
//Set up column sizes.
initColumnSizes(Table,My_Model);
//Add the scroll pane to this window.
if (Show_External_Table)
Table_Frame=new JFrame(Table_Name);
Table_Frame.getContentPane().add(scrollPane);
Table_Frame.addWindowListener(new WindowAdapter()
public void windowActivated(WindowEvent e) { }
public void windowClosed(WindowEvent e) { }
public void windowClosing(WindowEvent e) { System.exit(0); }
public void windowDeactivated(WindowEvent e) { }
public void windowDeiconified(WindowEvent e) { scrollPane.repaint(); }
public void windowGainedFocus(WindowEvent e) { scrollPane.repaint(); }
public void windowIconified(WindowEvent e) { }
public void windowLostFocus(WindowEvent e) { }
public void windowOpening(WindowEvent e) { scrollPane.repaint(); }
public void windowOpened(WindowEvent e) { }
public void windowResized(WindowEvent e) { scrollPane.repaint(); }
public void windowStateChanged(WindowEvent e) { scrollPane.repaint(); }
Table_Frame.pack();
Table_Frame.setBounds((Screen_Size.width-Table_Frame.getWidth())/2,(Screen_Size.height-Table_Frame.getHeight())/2,Table_Frame.getWidth(),Table_Frame.getHeight());
Table_Frame.setVisible(true);
if (Is_Child) Table_Frame.addComponentListener(new ComponentAdapter() { public void componentClosing(ComponentEvent e) { System.exit(0); } });
else add(scrollPane);
public Table_Panel(String File_Name) { this(File_Name,false,Row_Color_Style_Cyan_Gray,Preffered_Width,null,Default_Selection_Color,true); }
public Table_Panel(String File_Name,int Row_Color_Style,boolean In_Original_Order) { this(File_Name,false,Row_Color_Style,Preffered_Width,null,Default_Selection_Color,In_Original_Order); }
public Table_Panel(String File_Name,String Delimiter,boolean In_Original_Order) { this(File_Name,false,Row_Color_Style_Cyan_Gray,Preffered_Width,Delimiter,Default_Selection_Color,In_Original_Order); }
public Table_Panel(String File_Name,int Preffered_Width,String Delimiter,boolean In_Original_Order) { this(File_Name,false,Row_Color_Style,Preffered_Width,Delimiter,Default_Selection_Color,In_Original_Order); }
public Table_Panel(String File_Name,int Row_Color_Style,int Preffered_Width,String Delimiter,boolean In_Original_Order) { this(File_Name,false,Row_Color_Style,Preffered_Width,Delimiter,Default_Selection_Color,In_Original_Order); }
public Table_Panel(String File_Name,boolean Show_External_Table,boolean In_Original_Order) { this(File_Name,Show_External_Table,Row_Color_Style,Preffered_Width,null,Default_Selection_Color,In_Original_Order); }
public Table_Panel(String File_Name,boolean Show_External_Table,String Delimiter,boolean In_Original_Order) { this(File_Name,Show_External_Table,Row_Color_Style,Preffered_Width,Delimiter,Default_Selection_Color,In_Original_Order); }
public Table_Panel(String File_Name,boolean Show_External_Table,int Row_Color_Style,int Preffered_Width,String Delimiter,Color Selection_Color,boolean In_Original_Order)
String Table_Column_Names[],Column_Name_Line="";
int Row_Count=0,Index=0;
boolean Is_Child=false,Manage_Attachment=false;
StringTokenizer ST;
if (Delimiter==null) Delimiter=Default_Delimiter;
if (new File(File_Name).exists())
try
String Line,Str=Tool_Lib.Read_File(File_Name).toString();
ST=new StringTokenizer(Str,"\n");
Line=ST.nextToken();
Row_Count=ST.countTokens();
Object[][] Table_Data=new Object[Row_Count][];
if (Delimiter.equals(" ")) Line=Line.replaceAll(" {2,}"," ").trim(); // Replace multiple spaces with the delimiter space
Table_Column_Names=Line.split(Delimiter);
columnNames=Table_Column_Names;
for (int i=0;i<Table_Column_Names.length;i++) Column_Name_Line+=Table_Column_Names[i]+" ";
//Out("Column_Name_Line [ "+Table_Column_Names.length+" ]="+Column_Name_Line);
while (ST.hasMoreTokens())
Line=ST.nextToken();
//Out(Line);
if (Delimiter.equals(" ")) Line=Line.replaceAll(" {2,}"," ").trim(); // Replace multiple spaces with the delimiter space
if (Line.indexOf(Delimiter)!=-1) Table_Data[Index]=Line.split(Delimiter);
else
Table_Data[Index]=new Object[Table_Column_Names.length];
Table_Data[Index][0]=Line;
for (int i=1;i<Table_Column_Names.length;i++) Table_Data[Index]="";
Index++;
Line="";
for (int i=0;i<Table_Data.length;i++)
Line+="[ "+Table_Data[i].length+" ] ";
for (int j=0;j<Table_Data[i].length;j++) Line+=Table_Data[i][j]+" ";
Line+="\n";
Out(Line);
Table_Panel A_Table_Panel=new Table_Panel(File_Name,Table_Column_Names,Table_Data,Row_Count,Is_Child,Show_External_Table,Manage_Attachment,Row_Color_Style,Preffered_Width,Selection_Color,In_Original_Order);
Table=A_Table_Panel.Table;
scrollPane=A_Table_Panel.scrollPane;
Column_Width=A_Table_Panel.Column_Width;
data=A_Table_Panel.data;
catch (Exception e) { e.printStackTrace(); }
public void setPreferredSize(Dimension A_Dimension) { scrollPane.setPreferredSize(A_Dimension); }
// This method picks good column sizes. If all column heads are wider than the column's cells' contents, then you can just use column.sizeWidthToFit().
void initColumnSizes(JTable table,TableModel model)
TableColumn column=null;
Component comp=null;
int headerWidth=0,cellWidth=0;
Object[] longValues=(data.length>0)?data[0]:null;
TableCellRenderer headerRenderer=table.getTableHeader().getDefaultRenderer();
if (data.length<1) return;
for (int i=0;i<model.getColumnCount();i++)
column=table.getColumnModel().getColumn(i);
comp=headerRenderer.getTableCellRendererComponent(null,column.getHeaderValue(),false,false,0,0);
headerWidth=comp.getPreferredSize().width;
comp=table.getDefaultRenderer(model.getColumnClass(i)).
getTableCellRendererComponent(table,longValues[i],false,false,0,i);
cellWidth=comp.getPreferredSize().width;
switch (Preffered_Width)
case Max_Header_Cell_Width : column.setPreferredWidth(Math.max(headerWidth,cellWidth));break;
case Header_Width : column.setPreferredWidth(headerWidth);break;
case Cell_Width : column.setPreferredWidth(cellWidth);break;
Column_Width[i]=column.getPreferredWidth();
if (Debug) Out("Initializing width of column "+i+". "+"headerWidth="+headerWidth+"; cellWidth="+cellWidth+" Column_Width["+i+"]="+Column_Width[i]);
// Detects a state change in any of the Lists. Resets the variable corresponding to the selected item in a particular List. Invokes changeFont with the currently selected fontname, style and size attributes.
public void itemStateChanged(ItemEvent e)
Out(e.toString());
if (e.getStateChange() != ItemEvent.SELECTED) return;
Object list=e.getSource();
public static void Out(String message) { System.out.println(message); }
// Create the GUI and show it. For thread safety, this method should be invoked from the event-dispatching thread.
static void Create_And_Show_GUI()
boolean Demo_External_Table=true;
// boolean Demo_External_Table=false;
final Table_Panel demo;
String[] columnNames={"First Names","Last Names","Sport","Num of Years","Vegetarian"};
Object[][] data={{"Mary","Campione","Snowboarding"+"[123456789]",new Integer(5),new Boolean(false)},
{"Alison","Huml","Rowing"+":123456789]",new Integer(3),new Boolean(true)},
{"Frank","Ni","Running"+":123456789", new Integer(12), new Boolean(false)},
{"Kathy","Walrath","Chasing toddlers"+"<123456789>", new Integer(2), new Boolean(false)},
{"Mark", "Andrews","Speed reading",new Integer(20),new Boolean(true)},
{"Angela","Lih","Teaching high school",new Integer(36),new Boolean(false)} };
// Row_Color_Style=Row_Color_Style_Default;
// Row_Color_Style=Row_Color_Style_None;
// Row_Color_Style=Row_Color_Style_Blue_Gray;
Row_Color_Style=Row_Color_Style_Cyan_Gray;
// Row_Color_Style=Row_Color_Style_Blue;
// Row_Color_Style=Row_Color_Style_Gray;
// Row_Color_Style=Row_Color_Style_Red_Green;
// Row_Color_Style=Row_Color_Style_Green_Yellow;
// Row_Color_Style=Row_Color_Style_Red_Yellow;
Preffered_Width=Max_Header_Cell_Width;
if (Demo_External_Table) demo=new Table_Panel("External Table Demo",columnNames,data,data.length,false,Demo_External_Table,false,Row_Color_Style,Max_Header_Cell_Width,Default_Selection_Color,true);
else
JFrame Table_Frame=new JFrame("Internal Table Demo");
// demo=new Table_Panel(Nm_Lib.Dir_A_Test+"ELX.csv",false,Row_Color_Style,Preffered_Width,null);
// demo=new Table_Panel(Nm_Lib.Dir_Stock_Data+"ABV_Data.txt",false,Row_Color_Style,Preffered_Width," ");
demo=new Table_Panel("C:/Dir_Stock_Data/EOP.txt",",",false);
// demo=new Table_Panel(Nm_Lib.Dir_Stock_Data+"ABV_Data.txt"," ",false);
Table_Frame.getContentPane().add(demo.scrollPane);
Table_Frame.addWindowListener(new WindowAdapter()
public void windowActivated(WindowEvent e) { }
public void windowClosed(WindowEvent e) { }
public void windowClosing(WindowEvent e) { System.exit(0); }
public void windowDeactivated(WindowEvent e) { }
public void windowDeiconified(WindowEvent e) { demo.repaint(); }
public void windowGainedFocus(WindowEvent e) { demo.repaint(); }
public void windowIconified(WindowEvent e) { }
public void windowLostFocus(WindowEvent e) { }
public void windowOpening(WindowEvent e) { demo.repaint(); }
public void windowOpened(WindowEvent e) { }
public void windowResized(WindowEvent e) { demo.repaint(); }
public void windowStateChanged(WindowEvent e) { demo.repaint(); }
Table_Frame.pack();
Table_Frame.setBounds((Screen_Size.width-Table_Frame.getWidth())/2,(Screen_Size.height-Table_Frame.getHeight())/2,Table_Frame.getWidth(),Table_Frame.getHeight());
Table_Frame.setVisible(true);
public static void main(String[] args)
// Schedule a job for the event-dispatching thread : creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() { public void run() { Create_And_Show_GUI(); } });
* TableSorter is a decorator for TableModels; adding sorting functionality to a supplied TableModel. TableSorter does not store
* or copy the data in its TableModel; instead it maintains a map from the row indexes of the view to the row indexes of the
* model. As requests are made of the sorter (like getValueAt(row, col)) they are passed to the underlying model after the row numbers
* have been translated via the internal mapping array. This way, the TableSorter appears to hold another copy of the table
* with the rows in a different order.
* <p/>
* TableSorter registers itself as a listener to the underlying model, just as the JTable itself would. Events recieved from the model
* are examined, sometimes manipulated (typically widened), and then passed on to the TableSorter's listeners (typically the JTable).
* If a change to the model has invalidated the order of TableSorter's rows, a note of this is made and the sorter will resort the
* rows the next time a value is requested.
* <p/>
* When the tableHeader property is set, either by using the setTableHeader() method or the two argument constructor, the table
* header may be used as a complete UI for TableSorter. The default renderer of the tableHeader is decorated with a renderer
* that indicates the sorting status of each column. In addition, a mouse listener is installed with the following behavior:
* <ul>
* <li>
* Mouse-click: Clears the sorting status of all other columns and advances the sorting status of that column through three
* values: {NOT_SORTED, ASCENDING, DESCENDING} (then back to NOT_SORTED again).
* <li>
* SHIFT-mouse-click: Clears the sorting status of all other columns and cycles the sorting status of the column through the same
* three values, in the opposite order: {NOT_SORTED, DESCENDING, ASCENDING}.
* <li>
* CONTROL-mouse-click and CONTROL-SHIFT-mouse-click: as above except that the changes to the column do not cancel the statuses of columns
* that are already sorting - giving a way to initiate a compound sort.
* </ul>
* <p/>
* This is a long overdue rewrite of a class of the same name that first appeared in the swing table demos in 1997.
* @author Philip Milne
* @author Brendon McLean
* @author Dan van Enckevort
* @author Parwinder Sekhon
* @version 2.0 02/27/04
class TableSorter extends AbstractTableModel
public static final long serialVersionUID=26362862L;
protected TableModel tableModel;
public static final int DESCENDING = -1;
public static final int NOT_SORTED = 0;
public static final int ASCENDING = 1;
private static Directive EMPTY_DIRECTIVE = new Directive(-1, NOT_SORTED);
public static final Comparator COMPARABLE_COMAPRATOR = new Comparator() { public int compare(Object o1, Object o2) { return ((Comparable) o1).compareTo(o2); } };
public static final Comparator LEXICAL_COMPARATOR = new Comparator() { public int compare(Object o1, Object o2) { return o1.toString().compareTo(o2.toString()); } };
private Row[] viewToModel;
private int[] modelToView;
private JTableHeader tableHeader;
private MouseListener mouseListener;
private TableModelListener tableModelListener;
private Map<Class,Comparator> columnComparators = new HashMap<Class,Comparator>();
private List<Directive> sortingColumns = new ArrayList<Directive>();
public TableSorter()
this.mouseListener = new MouseHandler();
this.tableModelListener = new TableModelHandler();
public TableSorter(TableModel tableModel)
this();
setTableModel(tableModel);
public TableSorter(TableModel tableModel, JTableHeader tableHeader)
this();
setTableHeader(tableHeader);
setTableModel(tableModel);
private void clearSortingState()
viewToModel = null;
modelToView = null;
public TableModel getTableModel() { return tableModel; }
public void setTableModel(TableModel tableModel)
if (this.tableModel != null) { this.tableModel.removeTableModelListener(tableModelListener); }
this.tableModel = tableModel;
if (this.tableModel != null) { this.tableModel.addTableModelListener(tableModelListener); }
clearSortingState();
fireTableStructureChanged();
public JTableHeader getTableHeader() { return tableHeader; }
public void setTableHeader(JTableHeader tableHeader)
if (this.tableHeader != null)
this.tableHeader.removeMouseListener(mouseListener);
TableCellRenderer defaultRenderer = this.tableHeader.getDefaultRenderer();
if (defaultRenderer instanceof SortableHeaderRenderer) this.tableHeader.setDefaultRenderer(((SortableHeaderRenderer) defaultRenderer).tableCellRenderer);
this.tableHeader = tableHeader;
if (this.tableHeader != null)
this.tableHeader.addMouseListener(mouseListener);
this.tableHeader.setDefaultRenderer(
new SortableHeaderRenderer(this.tableHeader.getDefaultRenderer()));
public boolean isSorting() { return sortingColumns.size() != 0; }
private Directive getDirective(int column)
for (int i = 0; i < sortingColumns.size(); i++)
Directive directive = (Directive)sortingColumns.get(i);
if (directive.column == column) { return directive; }
return EMPTY_DIRECTIVE;
public int getSortingStatus(int column) { return getDirective(column).direction; }
private void sortingStatusChanged()
clearSortingState();
fireTableDataChanged();
if (tableHeader != null) { tableHeader.repaint(); }
public void setSortingStatus(int column, int status)
Directive directive = getDirective(column);
if (directive != EMPTY_DIRECTIVE) { sortingColumns.remove(directive); }
if (status != NOT_SORTED) { sortingColumns.add(new Directive(column, status)); }
sortingStatusChanged();
protected Icon getHeaderRendererIcon(int column, int size)
Directive directive = getDirective(column);
if (directive == EMPTY_DIRECTIVE) { return null; }
return new Arrow(directive.direction == DESCENDING, size, sortingColumns.indexOf(directive));
private void cancelSorting()
sortingColumns.clear();
sortingStatusChanged();
public void setColumnComparator(Class type, Comparator comparator)
if (comparator == null) { columnComparators.remove(type); }
else { columnComparators.put(type, comparator); }
protected Comparator getComparator(int column)
Class columnType = tableModel.getColumnClass(column);
Comparator comparator = (Comparator) columnComparators.get(columnType);
if (comparator != null) { return comparator; }
if (Comparable.class.isAssignableFrom(columnType)) { return COMPARABLE_COMAPRATOR; }
return LEXICAL_COMPARATOR;
private Row[] getViewToModel()
if (viewToModel == null)
int tableModelRowCount = tableModel.getRowCount();
viewToModel = new Row[tableModelRowCount];
for (int row = 0; row < tableModelRowCount; row++) { viewToModel[row] = new Row(row); }
if (isSorting()) { Arrays.sort(viewToModel); }
return viewToModel;
public int modelIndex(int viewIndex) { return getViewToModel()[viewIndex].modelIndex; }
private int[] getModelToView()
if (modelToView == null)
int n = getViewToModel().length;
modelToView = new int[n];
for (int i = 0; i < n; i++) { modelToView[modelIndex(i)] = i; }
return modelToView;
// TableModel interface methods
public int getRowCount() { return (tableModel == null) ? 0 : tableModel.getRowCount(); }
public int getColumnCount() { return (tableModel == null) ? 0 : tableModel.getColumnCount(); }
public String getColumnName(int column) { return tableModel.getColumnName(column); }
public Class getColumnClass(int column) { return tableModel.getColumnClass(column); }
public boolean isCellEditable(int row, int column) { return tableModel.isCellEditable(modelIndex(row), column); }
public Object getValueAt(int row, int column) { return tableModel.getValueAt(modelIndex(row), column); }
public void setValueAt(Object aValue, int row, int column) { tableModel.setValueAt(aValue, modelIndex(row), column); }
// Helper classes
private class Row implements Comparable
private int modelIndex;
public Row(int index) { this.modelIndex = index; }
public int compareTo(Object o)
int row1 = modelIndex;
int row2 = ((Row) o).modelIndex;
for (Iterator it = sortingColumns.iterator(); it.hasNext();)
Directive directive = (Directive) it.next();
int column = directive.column;
Object o1 = tableModel.getValueAt(row1, column);
Object o2 = tableModel.getValueAt(row2, column);
int comparison = 0;
// Define null less than everything, except null.
if (o1 == null && o2 == null) { comparison = 0; }
else if (o1 == null) { comparison = -1; }
else if (o2 == null) { comparison = 1; }
else { comparison = getComparator(column).compare(o1, o2); }
if (comparison != 0) { return directive.direction == DESCENDING ? -comparison : comparison; }
return 0;
private class TableModelHandler implements TableModelListener
public void tableChanged(TableModelEvent e)
// If we're not sorting by anything -
Color a row in JTable according to specific column value
I'm having problem setting row color according to specific values set in listData. Color values are also stored inside the listData. Each row has a specific color value assigned to it(either black or blue).
ColorRenderer is called from table.setDefaultRenderer(Object.class, new ColorRenderer(listData))
The color values are passed through to ColorRender constructor but not to the getTableCellRendererComponent() method.
Here is my code. Any help is much appreciated.
class ColorRenderer extends DefaultTableCellRenderer {
Color[] colors;
public ColorRenderer(ListData[] listData) {
if (listData != null) {
for (int i=0; i<listData.length; i++) {
if (listData[i] != null) {
colors = new Color[listData.length];
colors[i] = listData.getForegroundColor();
System.out.println(colors[i].toString());
else System.out.println("null listData");
public Component getTableCellRendererComponent (JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
JLabel c =(JLabel)super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
c.setOpaque(true);
System.out.println("colors.length: " + colors.length);
for (int i=0; i<colors.length; i++) {
if (colors[i] != null) {
System.out.println("colors["+i+"]: " + colors[i]);
c.setForeground(colors[i]);
} else c.setForeground(Color.black);
return c;Well, first of all, you didn't use the code tokens for your posting. Second, this source won't even compile how you have it. But anyway...
If you want to change the color of the cell based on the row, assuming you have a matching color in your color list for each row, in your getTableCellRendererComponent() method, just do something like this.
c.setForeground( colors[row] ); -
To change the font of a selected row in a Jtable
Hello,
Is it possible to change the font of a selected row in a jtable?
i.e. if all the table is set to a bold font, how would you change the font of the row selected to a normal (not bold) font?
thank you.String will be left justified
Integer will be right justified
Date will be a simple date without the time.
As it will with this renderer.Only if your custom renderer duplicates the code
found in each of the above renderers. This is a waste
of time to duplicate code. The idea is to reuse code
not duplicate and debug again.
No, no, no there will be NO duplicated code.
A single renderer class can handle all types ofdata.
Sure you can fit a square peg into a round hole if
you work hard enough. Why does the JDK come with
separate renderers for Date, Integer, Double, Icon,
Boolean? So that, by default the rendering for common classes is done correctly.
Because its a better design then having code
with a bunch of "instanceof" checks and nested
if...else code.This is only required for customization BEYOND what the default renderers provide
>
And you would only have to use instanceof checkswhen you required custom
rendering for a particular classAgreed, but as soon as you do require custom
renderering you need to customize your renderer.
which you would also have to do with theprepareRenderer calls too
Not true. The code is the same whether you treat
every cell as a String or whether you use a custom
renderer for every cell. Here is the code to make the
text of the selected line(s) bold:
public Component prepareRenderer(TableCellRenderer
renderer, int row, int column)
Component c = super.prepareRenderer(renderer, row,
, column);
if (isRowSelected(row))
c.setFont( c.getFont().deriveFont(Font.BOLD) );
return c;
}It will work for any renderer used by the table since
the prepareRenderer(...) method returns a Component.
There is no need to do any kind of "instanceof"
checking. It doesn't matter whether the cell is
renderered with the "Object" renderer or the
"Integer" renderer.
If the user wants to treat all columns as Strings or
treat individual columns as String, Integer, Data...,
then they only need to override the getColumnClass()
method. There is no change to the prepareRenderer()
code.
Have you actually tried the code to see how simple it
is?
I've posted my code. Why don't you post your solution
that will allow the user to bold the text of a Date,
Integer, and String data in separate column and then
let the poster decide.Well, I don't see a compilable, runnable demo anywhere in this thread. So here's one
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Vector;
public class TableRendererDemo extends JFrame{
String[] headers = {"String","Integer","Float","Boolean","Date"};
private JTable table;
public TableRendererDemo() {
buildGUI();
private void buildGUI() {
JPanel mainPanel = (JPanel) getContentPane();
mainPanel.setLayout(new BorderLayout());
Vector headerVector = new Vector(Arrays.asList(headers));
Vector data = createDataVector();
DefaultTableModel tableModel = new DefaultTableModel(data, headerVector){
public Class getColumnClass(int columnIndex) {
return getValueAt(0,columnIndex).getClass();
table = new JTable(tableModel);
// table.setDefaultRenderer(Object.class, new MyTableCellRenderer());
table.setDefaultRenderer(String.class, new MyTableCellRenderer());
table.setDefaultRenderer(Integer.class, new MyTableCellRenderer());
table.setDefaultRenderer(Float.class, new MyTableCellRenderer());
table.setDefaultRenderer(Date.class, new MyTableCellRenderer());
JScrollPane jsp = new JScrollPane(table);
mainPanel.add(jsp, BorderLayout.CENTER);
pack();
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
private Vector createDataVector(){
Vector dataVector = new Vector();
for ( int i = 0 ; i < 10; i++){
Vector rowVector = new Vector();
rowVector.add(new String("String "+i));
rowVector.add(new Integer(i));
rowVector.add(new Float(1.23));
rowVector.add( (i % 2 == 0 ? Boolean.TRUE : Boolean.FALSE));
rowVector.add(new Date());
dataVector.add(rowVector);
return dataVector;
public static void main(String[] args) {
Runnable runnable = new Runnable() {
public void run() {
TableRendererDemo tableRendererDemo = new TableRendererDemo();
tableRendererDemo.setVisible(true);
SwingUtilities.invokeLater(runnable);
class MyTableCellRenderer extends DefaultTableCellRenderer{
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if ( isSelected){
setFont(getFont().deriveFont(Font.BOLD));
else{
setFont(getFont().deriveFont(Font.PLAIN));
if ( value instanceof Date){
SimpleDateFormat formatter =(SimpleDateFormat) SimpleDateFormat.getDateInstance(DateFormat.MEDIUM);
setText(formatter.format((Date)value));
if(value instanceof Number){
setText(((Number)value).toString());
return this;
}Hardly a "bunch of instanceof or nested loops. I only used the Date instanceof to allow date format to be specified/ modified. If it was left out the Date column would be "18 Apr 2005" ( DateFormat.MEDIUM, which is default).
Cheers
DB -
Hello everyone,
I dont have a whole lot of experience w/ JTables and this problem has been troubling me for a while now. I have a JTable that significantly changes when the user hits the calculate button, so instead of going through the trouble of completely reformatting the table by adding/removing columns and table headers, I simple make a new model and set the table's model to the new one, and then call table.updateUI(). The problem is that my custom cell renderer that displays a down or up arrow depending on how the given column is sorted stops working. The sorter works properly and the table displays properly, but the arrows do not change from up to down or vise versa when a column is resorted. The whole process works just fine the first time, but the more times the user pushes the calculate button the more off it gets. I have added a flag in the actionPerformed method in my cell renderer that tells me when the table header is clicked. Every time the calculate button is hit, more flags appear when the table header is clicked. Therefore the arrows change position on odd numbers and do not on evens (because the evens cancel eachother out and the arrow appears to sit still), however the sorter still works properly. It seems as though somehow a new mouse listener or cell renderer is added after each time the calculate button is pressed. Either that or the entire table is not being reset somehow and something is still invisible in the background.
Here is some of my code.
// The initial table with no data
String[] str = {"class 1", "class 2", "class 3", "class 4", "class 5", "= GPA"};
String[][] data= {{"", "", "", "", "", ""},
pmModel = new ProjectionModel(str, data);
mainTable = new JTable(pmModel);
mainTable.getTableHeader().setDefaultRenderer(new SortButtonRenderer());
// After the calculate button has been pushed:
// The table is reset here. TableSorter extends TableMap
ProjectionModel newModel = new ProjectionModel(courseList, charList);
TableSorter sorter = new TableSorter(newModel);
// this method is shown below
sorter.addMouseListenerToHeaderInTable(mainTable);
sorter.sortedUp = false;
mainTable.addNotify();
mainTable.setModel(sorter);
// SortButtonRenderer extends TableCellRenderer
SortButtonRenderer renderer = new SortButtonRenderer();
mainTable.getTableHeader().setDefaultRenderer(renderer);
// set the arrow to DOWN on the first column
renderer.setSelectedColumn(0);
renderer.setSelectedColumn(0);
mainTable.updateUI();
// This is the addMouseListenerToTable(JTable table) found in the TableSorter class
public void addMouseListenerToHeaderInTable(JTable table) {
final TableSorter sorter = this;
final JTable tableView = table;
tableView.setColumnSelectionAllowed(false);
MouseAdapter listMouseListener = new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
TableColumnModel columnModel = tableView.getColumnModel();
int viewColumn = columnModel.getColumnIndexAtX(e.getX());
int column = tableView.convertColumnIndexToModel(viewColumn);
if (e.getClickCount() == 1 && column != -1) {
SortButtonRenderer renderer =
(SortButtonRenderer)tableView.getTableHeader().getDefaultRenderer();
//int shiftPressed = e.getModifiers()&InputEvent.SHIFT_MASK;
//boolean ascending = (shiftPressed == 0);
boolean ascending = (renderer.getLastColumn() == column && !sortedUp);
renderer.setLastColumn(column);
sorter.sortByColumn(column, ascending);
if (ascending) sortedUp = true;
else sortedUp = false;
renderer.setSelectedColumn(column);
// the flag that prints the column that is pressed
System.out.println(column + " " + sortedUp);
JTableHeader th = tableView.getTableHeader();
th.addMouseListener(listMouseListener); // it seems like i need a way to remove any
// previous mouseListeners here, i think this would solve the problem
}The flag's output looks something like this:
< first time calculate button is clicked >
< column 0 is clicked> 0 false
< column 0 is clicked again > 0 true
< second time calculate button is clicked >
< column 0 is clicked >
0 false
0 true
notice they cancel eachother out so the arrow stays in the same position
< third time calculate button is clicked >
< column 0 is clicked >
0 false
0 true
0 false
notice they dont cancel eachother out, so the arrow changes positions
This problem is really bugging me. I appreciate any help. Thanks.
-kcWell I fixed my problem but I kind of cheated...
I used a static variable in the class that inits the GUI to keep track of the MouseListeners that are added to the table headers by the TableSorter. In the TableSorter class's addMouseListenerToTableHeader(JTable table) class I added a line of code before the "th.addMouseListener(listListener)" line: "th.removeMouseListener(Projector.lastListener))"
It works but it kind of sucks. If there is a better way to do it that would be great. I'm sorry if you read through all of that stuff and then I ended up fixing my own problem anyway :(
Thanks anyway.
-kc
Maybe you are looking for
-
Airplay is not working after the last updates
Hello, I've updated iphone, ipad air and ipad 4 to ios 8 and apple tv 3 (1469) to newest version (7?). After that it's absolutely a disaster. Mostly I using the apple tv for music streaming, sometimes for mirroring... But it can not be found, I can n
-
Report painter report in portal - Excel output in SAP GUI for HTML
Dear sirs, I need your expertize. I would like to let my users display (Excel in place)/ save the result of my report painter reports into MS Excel. I have found notes 499262 a 314568, but didn´t understand the message (or there is no message:)). Doe
-
So I recently bought my MacBook Pro, about three days ago, and the wifi connection is horrible. I can barely access anything on the internet. I tried using my PC laptop, and the wifi worked very quickly, so the problem definitely isn't my wifi connec
-
Hi, po_headers_sv3.get_po_status is not returning any value when used in an RDF report. But, when I set the MO Context in TOAD/SQL*Plus and running the same query, it is returning the status. EBS Version : R12.1.3 Oracle Forms Version : 10g Below is
-
G62-454ca won't turn on.power led and wireless network led keeps blinking every 3-4 seconds
Please help.when I try to turn on nothing happens.Only power LED and wireless network led keeps blinking every 4 seconds