• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Color in JTable

 
Ranch Hand
Posts: 211
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
How to give different Color in JTable rows and Cells.
 
Bartender
Posts: 4121
IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You'll need to make a custom TableCellRenderer... check out the Swing Tutorial section on editors and renderers. You'll need to scroll down the page a bit to get to the renderers.
 
Mathews P Srampikal
Ranch Hand
Posts: 211
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
OK.But how make the whole row in a different color,irrespective of the class in the Cell.I mean I don't want to give like this
table.setDefaultRenderer( Class.forName( "java.lang.Integer" ), renderer );
because my row may contain Integer,String,Date etc.But depending on some other validation i have to make the Whole row in different color.
 
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If you register with Object.class ie.


it will apply to all rows in the table. From the API entry for getDefaultRenderer() :
Returns the cell renderer to be used when no renderer has been set in a TableColumn. During the rendering of cells the renderer is fetched from a Hashtable of entries according to the class of the cells in the column. If there is no entry for this columnClass the method returns the entry for the most specific superclass. The JTable installs entries for Object, Number, and Boolean, all of which can be modified or replaced.
D.
[ February 17, 2004: Message edited by: Don Kiddick ]
 
Mathews P Srampikal
Ranch Hand
Posts: 211
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Still the problem is not solved....
if i put this code in my Renderer class
public Component getTableCellRendererComponent
(JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column) {
Component cell = super.getTableCellRendererComponent
(table, value, isSelected, hasFocus, row, column);

if(row==0){
cell.setBackground(Color.RED);.
}
return cell;
}
 
Don Kiddick
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
What problem are you seeing ?
That works for me, it makes the first row go red.
 
Ranch Hand
Posts: 100
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
is setOpaque(true)?
 
Mathews P Srampikal
Ranch Hand
Posts: 211
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I am getting all the rows in RED only.where we have to make
setOpaque(true);This is in the renderer method or in the main table
 
Don Kiddick
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Instead of :

try :

D.
 
Mathews P Srampikal
Ranch Hand
Posts: 211
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yes.Now it is working.Now the problem is this color is not depending on the row,value or column or anything in the JTable.It is depending on the other 5 values (Status 1,2,3,4,5) coming from the database.These status is not displayed in the table So how to get ride of this by Logically.
 
Don Kiddick
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You need to put enough information in your table model for your renderer to work out what colour it needs to draw the cell.
D.
 
Mathews P Srampikal
Ranch Hand
Posts: 211
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks don,Now can you tell me how to refresh the JTable like our JSP.I know AbstractTableModel and DefaultTableModel.But this has to happen dynamically.Because in the database Insertion,Updation and deletion may happen.So can you please give a small example with 2 column and 2 rows.But table has to refresh even somebody Manually change or delete value from the database.
 
Don Kiddick
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Look at
fireTableDataChanged()
fireTableCellUpdated(int row, int column)
fireTableRowsDeleted(int firstRow, int lastRow)
fireTableRowsInserted(int firstRow, int lastRow)
fireTableRowsUpdated(int firstRow, int lastRow)
in AbstractTableModel().
If you're just using DefaultTableModel and using setValueAt() to update then you don't have to worry about this as setValueAt will call these methods for you. If you've rolled your own TableModel, then you probably do.
No time for a example now...
D.
 
Don Kiddick
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If you let us know some more information on what you're trying to do, we can help you better.
What information your displaying, how it should be displayed, how the information gets updated etc...
D.
 
Mathews P Srampikal
Ranch Hand
Posts: 211
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Actually when the data is Updated in the database it has to be reflected in the table. I reached somewhere doing some research.I will post that both the classes here Main Class amd Model Class
My Model Class is>>>>>>>>>>>>>>>>>>>>>>
import javax.swing.table.AbstractTableModel;
import javax.swing.event.TableModelEvent;
import java.util.Vector;
import java.util.Hashtable;
import java.util.HashMap;
import java.util.Date;
class FaultTableModel extends AbstractTableModel {
privatestatic StringcolumnNames[];
privatestatic Objectdata[][];

Vector vectData=new Vector();

FaultTableModel(){
Vector vectData=new Vector();
HashMap hmValues=new HashMap();
int intStatus=20;

for(int i=1;i<21;i++){
hmValues=new HashMap();
hmValues.put("STATUS",intStatus+"");
hmValues.put("FAULTID",new Integer(i+100)+"");
hmValues.put("DATE",new Date()+"");
hmValues.put("SOURCE","Source "+i);
hmValues.put("DESC","Description "+i);
hmValues.put("COUNT",new Integer(i+200)+"");
hmValues.put("ASSIGNEDTO","Assigned To "+i);
intStatus++;
vectData.add(hmValues);
}

CreateColumns();
CreateData(vectData);
}
public void CreateColumns(){
// Create column string labels
columnNames = new String[7];
columnNames[0]="Status";
columnNames[1]="Fault ID";
columnNames[2]="Date Time";
columnNames[3]="Source";
columnNames[4]="Description";
columnNames[5]="Count";
columnNames[6]="Assigned To";

}
public void CreateData(Vector vector){
// Create data for each element
System.out.println("Vector Size = "+vector.size());
int intRows=vector.size();
data = new Object[intRows][7];

for( int iY = 0; iY < intRows; iY++ ){
HashMap hm=(HashMap)vector.elementAt(iY);
Object strStatus=hm.get("STATUS");
Object intFaultID=hm.get("FAULTID");
Object date=hm.get("DATE");
Object strSource=hm.get("SOURCE");
Object strDesc=hm.get("DESC");
Object intCount=hm.get("COUNT");
Object strAssigned=hm.get("ASSIGNEDTO");

data[iY][0] =strStatus;
data[iY][1] =intFaultID;
data[iY][2] =date;
data[iY][3] =strSource;
data[iY][4] =strDesc;
data[iY][5] =intCount;
data[iY][6] =strAssigned;

}
}
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) {
return data[row][col];
}
/*
* 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 < 1) {
return false;
} else {
return true;
}*/
return false;
}
/*
* Don't need to implement this method unless your table's
* data can change.
*/
public void setValueAt(Object value, int row, int col) {
data[row][col] = value;
fireTableCellUpdated(row, col);
}

public void tableChanged(TableModelEvent e) {
fireTableChanged(e);
}

public void set(){
int intStatus=1000;
vectData.clear();
vectData=new Vector();
for(int i=30;i<41;i++){
HashMap hmValues=new HashMap();
hmValues.put("STATUS",intStatus+"");
hmValues.put("FAULTID",new Integer(i+100)+"");
hmValues.put("DATE",new Date()+"");
hmValues.put("SOURCE","Source "+i);
hmValues.put("DESC","Description "+i);
hmValues.put("COUNT",new Integer(i+200)+"");
hmValues.put("ASSIGNEDTO","Assigned To "+i);
intStatus++;
vectData.add(hmValues);
}

CreateColumns();
CreateData(vectData);
}
}
My Main Class FaultMgmt Class is
import javax.swing.JComboBox;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
//import javax.swing.table.DefaultTableCellRenderer;
//import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
//import javax.swing.event.TableModelListener;
//import javax.swing.event.TableModelEvent;
//import javax.swing.event.ListSelectionListener;
//import javax.swing.event.ListSelectionEvent;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
//import java.awt.Component;
//import java.awt.Dimension;
//import java.awt.GridLayout;
//import java.sql.ResultSet;
import java.util.Hashtable;
import java.util.HashMap;
import java.util.Date;
public class FaultMgmt extends JPanel implements ActionListener{
JTable table;
FaultTableModel modal;
public void addComponentsToPane(Container pane) {

JTextField txtTotal=new JTextField(5);
JLabel lblDisplaying=new JLabel("Displaying");
JTextField txtFrom=new JTextField(5);
JLabel lblTo=new JLabel("To");
JTextField txtTo=new JTextField(5);
JLabel lblPgLength=new JLabel("Page Length");
JButton bt=new JButton("OK CHANGE IT");
bt.addActionListener(this);

modal=new FaultTableModel();
table = new JTable(modal);
//table = new JTable(new FaultTableModel());
table.setOpaque(true);
JScrollPane scrollPane = new JScrollPane(table);

pane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();

c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(0,5,0,5);
pane.add(txtTotal, c);
c.gridx = 1;
c.gridy = 0;
pane.add(lblDisplaying, c);
c.gridx = 2;
c.gridy = 0;
pane.add(txtFrom, c);

c.gridx = 3;
c.gridy = 0;
pane.add(lblTo, c);

c.gridx = 5;
c.gridy = 0;
pane.add(txtTo, c);
c.gridx = 6;
c.gridy = 0;
pane.add(lblPgLength, c);
c.gridx = 7;
c.gridy = 0;
pane.add(bt, c);
c.gridx = 0;
c.gridy = 1;
c.gridwidth = 8;
c.insets = new Insets(10,0,10,0); //Top 10 and Bottom 10 padding
pane.add(scrollPane, c);
}
public void actionPerformed(ActionEvent ae){
modal.set();
}
public static void main(String[] args) {
FaultMgmt fm = new FaultMgmt();
JFrame.setDefaultLookAndFeelDecorated(true);

JFrame frame = new JFrame("NMS Fault Management Systems");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
fm.addComponentsToPane(frame.getContentPane());
frame.setResizable(false);
frame.pack();
frame.setVisible(true);

}
}
While clicking on change Button Data has to Reflect in the table.but my requirement is whenever database changes.
You may please compile and run FaultMgmt class and see the result instead of 11 rows all the previouse 20 rows are coming.but after 11 rows all other rows are disabled.
 
Don Kiddick
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You are already using the fireTable* methods. So what problem(s) are you actually having ?
D.
 
Nathan Pruett
Bartender
Posts: 4121
IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It sounds like you want to update the table automatically whenever the actual data in the database changes. You don't get this *automatically* from JSPs either... JSPs get new data from the database every time the page is refreshed because it has to build the page from scratch, so it hits the database every time the JSP is requested. Here your table model is behaving like a cache... it's storing the database data locally. The only way you could do anything like what you want is to have a background thread that runs every so often that gets the data from the database and compares it to the data in your table model, and changes the data in the table model if anything is different.
 
Don Kiddick
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
unless you create a solution using triggers - but that would be a World of pain.
D.
 
Mathews P Srampikal
Ranch Hand
Posts: 211
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi All,
Database things OK.But I am Clicking a button that time the number of rows has become less but that is not reflected in the table.BUT IF YOU ARE CLICKING ON THE TABLE THEN THE ACTUAL DATA IS DISPLAYED WITHOUT ANY PROBLEM.
I agree that we have to use a background thread running to monitor that but the code i am given is not from the database rather on click of the button the number of rows are decreased.But that decrement is not reflected in the JTable until we click on the table rows.
Once you just copy paste and run you will understand the problem.
 
Don Kiddick
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Add fireTableDataChanged(); to the end of the FaultTableModel.set() method.
D.
 
Mathews P Srampikal
Ranch Hand
Posts: 211
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Done DON !!! Thank You.Now it is working perfect and started thinking about the Thread at back end.
By the buy you can give this Full code some where here so that all the peoples doubt will be cleared in one shot.Thanks You all again.
 
Mathews P Srampikal
Ranch Hand
Posts: 211
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I have a small problem now..that is from my renderer class if i set the column color it is coming correct.But if select any of the row,other columns background is different.But my SETTED column is working perfectly.
My main class i have registered renderer like this,
table.setDefaultRenderer(Object.class, renderer );
In my renderer class i am setting like this..
if(strValue.equals("Major") && column==0){
cell.setBackground(Color.ORANGE);
}else if(strValue.equals("Minor") && column==0){
cell.setBackground(Color.YELLOW);
}else if(strValue.equals("Critical") && column==0){
cell.setBackground(Color.RED);
}else if(strValue.equals("Information") && column==0){
cell.setBackground(Color.GREEN);
}else if(strValue.equals("Warning") && column==0){
cell.setBackground(Color.CYAN);
}else {
cell.setBackground(Color.WHITE);
}
The problem is column 3 and 4 selection background is white only,but others are default.i want to make these 3&4 column background also default.
3 and 4 are string object others are Integer and Date.
 
Don Kiddick
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I don't really understand your problem, is it something to so with the coloured columns being selected ?
Please can you explain ands perhaps post your renderer code.
D.
[ February 26, 2004: Message edited by: Don Kiddick ]
 
Mathews P Srampikal
Ranch Hand
Posts: 211
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I changed a lot from the previous classes.
I will paste the classes and No Database and Package. The problem is while clicking on any cell the Sorce and Description column is still in white others are default(some violet) color.I want to make sorce and description also into default.
The Interesting thing is that i am printing column without any condition on renderer class but only 0,3,4 is coming others are not printed.This 0,3,4 are String other Objects 1 int,2 Date and 5 also int.I don't know what is happening.
CustomTableCellRenderer.java
import java.awt.Component;
import java.awt.Color;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableCellEditor;
public class CustomTableCellRenderer extends DefaultTableCellRenderer {

public CustomTableCellRenderer(){

}
public Component getTableCellRendererComponent
(JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column) {
Component cell = super.getTableCellRendererComponent
(table, value, isSelected, hasFocus, row, column);

String strValue=value.toString().trim();
//This else if is for making the whole row in differnt color
System.out.println("Column = "+column);
if(strValue.equals("Major") && column==0){
cell.setBackground(Color.ORANGE);
}else if(strValue.equals("Minor") && column==0){
cell.setBackground(Color.YELLOW);
}else if(strValue.equals("Critical") && column==0){
cell.setBackground(Color.RED);
}else if(strValue.equals("Information") && column==0){
cell.setBackground(Color.GREEN);
}else if(strValue.equals("Warning") && column==0){
cell.setBackground(Color.CYAN);
}else {
cell.setBackground(Color.WHITE);
}



//This is for making only
/**
if(strValue.equals("Major") && column==0){
cell.setBackground(Color.CYAN);
}else if(column>0){
cell.setBackground(Color.LIGHT_GRAY);
}else if(strValue.equals("Minor") && column==0){
cell.setBackground(Color.GREEN);
}else if(column>0){
cell.setBackground(Color.LIGHT_GRAY);
}else if(strValue.equals("Critical") && column==0){
cell.setBackground(Color.RED);
}else if(column>0){
cell.setBackground(Color.LIGHT_GRAY);
}else if(strValue.equals("Information") && column==0){
cell.setBackground(Color.YELLOW);
}else if(column>0){
cell.setBackground(Color.LIGHT_GRAY);
}else if(strValue.equals("Warning") && column==0){
cell.setBackground(Color.BLUE);
}else if(column>0){
cell.setBackground(Color.LIGHT_GRAY);
}
*/
/**if( value instanceof Integer ){
Integer amount = (Integer) value;
if( amount.intValue() < 7 ){
cell.setBackground( Color.red );
// You can also customize the Font and Foreground this way
// cell.setForeground();
// cell.setFont();
}else{
cell.setBackground( Color.blue );
}
}
*/
return cell;
}//End of method getTableCellRendererComponent
}//End of Class
FaultTableModel.java

import javax.swing.JLabel;
import javax.swing.table.AbstractTableModel;
import javax.swing.event.TableModelEvent;
import javax.swing.JTable;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import java.awt.event.*;
import java.util.Vector;
import java.util.Hashtable;
import java.util.HashMap;
import java.util.Date;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
class FaultTableModel extends AbstractTableModel {
static final public ColumnData columnNames[] = {
new ColumnData( "Severity", JLabel.LEFT ),
new ColumnData( "Fault ID", JLabel.LEFT ),
new ColumnData( "Date Time", JLabel.LEFT ),
new ColumnData( "Source", JLabel.LEFT ),
new ColumnData( "Description", JLabel.LEFT ),
new ColumnData( "Count", JLabel.LEFT )
};
protected Vector vectData;
protected int m_sortCol = 0;
protected boolean m_sortAsc = true;
public FaultTableModel() {
vectData = new Vector();
setFaultData();
}

public void setFaultData() {
//vectData.removeAllElements();
vectData.addElement(new FaultData("Major",1000,new Date(),"S23","desc4",254));
vectData.addElement(new FaultData("Minor",1001,new Date(),"S32","desc2",300));
vectData.addElement(new FaultData("Critical",1002,new Date(),"S33","desc1",198));
vectData.addElement(new FaultData("Warning",1003,new Date(),"S355","desc5",467));
vectData.addElement(new FaultData("Information",1004,new Date(),"3S3","desc3",598));

Collections.sort(vectData, new
StockComparator(m_sortCol, m_sortAsc));
}

public int getRowCount() {
return vectData==null ? 0 : vectData.size();
}
public int getColumnCount() {
return columnNames.length;
}
public String getColumnName(int column) {
String str = columnNames[column].m_title;
//if (column==m_sortCol)
//str += m_sortAsc ? " �" : " �";
return str;
}
public Object getValueAt(int nRow, int nCol) {
if (nRow < 0 || nRow>=getRowCount())
return "";
FaultData row = (FaultData)vectData.elementAt(nRow);
switch (nCol) {
case 0: return new String(row.gstatus);
case 1: return new Integer(row.gfaultID);
case 2: return row.gdate;
case 3: return new String(row.gsource);
case 4: return new String(row.gdesc);
case 5: return new Integer(row.gcount);
}
return "";
}
/*
* 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) {
//System.out.println("Error = "+getValueAt(0, c).getClass());
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 < 1) {
return false;
} else {
return true;
}*/
return false;
}
/*
* Don't need to implement this method unless your table's
* data can change.
*/
public void setValueAt(Object value, int row, int col) {
//vectData[row][col] = value;
fireTableCellUpdated(row, col);
}


public void tableChanged(TableModelEvent e) {
fireTableChanged(e);
}

public void set(){
/*int intStatus=20;

Vector vectData=new Vector();
for(int i=30;i<41;i++){
HashMap hmValues=new HashMap();
hmValues.put("STATUS",intStatus+"");
hmValues.put("FAULTID",new Integer(i+100)+"");
hmValues.put("DATE",new Date()+"");
hmValues.put("SOURCE","Source "+i);
hmValues.put("DESC","Description "+i);
hmValues.put("COUNT",new Integer(i+200)+"");
hmValues.put("ASSIGNEDTO","Assigned To "+i);
intStatus++;
vectData.add(hmValues);
}
CreateColumns();
CreateData(vectData);
//fireTableDataChanged();
//fireTableStructureChanged();
*/
}
class ColumnListener extends MouseAdapter
{
protected JTable m_table;

public ColumnListener(JTable table) {
m_table = table;
}
public void mouseClicked(MouseEvent e) {
TableColumnModel colModel = m_table.getColumnModel();
int columnModelIndex = colModel.getColumnIndexAtX(e.getX());
int modelIndex = colModel.getColumn(columnModelIndex).getModelIndex();

if (modelIndex < 0)
return;
if (m_sortCol==modelIndex)
m_sortAsc = !m_sortAsc;
else
m_sortCol = modelIndex;
for (int i=0; i < columnNames.length; i++) {
TableColumn column = colModel.getColumn(i);
column.setHeaderValue(getColumnName(column.getModelIndex()));
}
m_table.getTableHeader().repaint();
Collections.sort(vectData, new
StockComparator(modelIndex, m_sortAsc));
m_table.tableChanged(
new TableModelEvent(FaultTableModel.this));
m_table.repaint();
}
}

}
class FaultData
{
public String gstatus;
public int gfaultID;
public Date gdate;
public String gsource;
public String gdesc;
public int gcount;

public FaultData(String status,int faultID,Date date,String source,String desc,int count) {
gstatus = status;
gfaultID = faultID;
gdate = date;
gsource = source;
gdesc = desc;
gcount = count;
}
}
class ColumnData
{
public String m_title;
// public int m_width;
public int m_alignment;
public ColumnData(String title, int alignment) {
m_title = title;
//m_width = width;
m_alignment = alignment;
}
}

class StockComparator implements Comparator
{
protected int m_sortCol;
protected boolean m_sortAsc;
public StockComparator(int sortCol, boolean sortAsc) {
m_sortCol = sortCol;
m_sortAsc = sortAsc;
}
public int compare(Object o1, Object o2) {
if(!(o1 instanceof FaultData) || !(o2 instanceof FaultData)){
return 0;
}

FaultData s1 = (FaultData)o1;
FaultData s2 = (FaultData)o2;

int result = 0;

switch (m_sortCol) {
case 0: // status
result = s1.gstatus.compareTo(s2.gstatus);
break;
case 1: // fault Id
int f1=s1.gfaultID;
int f2=s2.gfaultID;
if (f1<f2)
result=-1;
else
result=1;
break;
case 2: // date
//result = s1.gstatus.compareTo(s2.gstatus);
break;
case 3: // source
result = s1.gsource.compareTo(s2.gsource);
break;
case 4: // desc
result = s1.gdesc.compareTo(s2.gdesc);
break;
case 5: // count
int c1=s1.gcount;
int c2=s2.gcount;
if (c1<c2)
result=-1;
else
result=1;
break;
}
//System.out.println("Hos"+m_sortCol);
if (!m_sortAsc)
result = -result;

return result;
}
public boolean equals(Object obj) {
System.out.println(obj);
if (obj instanceof StockComparator) {
StockComparator compObj = (StockComparator)obj;
return (compObj.m_sortCol==m_sortCol) &&
(compObj.m_sortAsc==m_sortAsc);
}
return false;
}
}

FaultMgmt.java

//import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
//import javax.swing.table.DefaultTableCellRenderer;
//import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
//import javax.swing.event.TableModelListener;
//import javax.swing.event.TableModelEvent;
//import javax.swing.event.ListSelectionListener;
//import javax.swing.event.ListSelectionEvent;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
//import java.awt.Component;
//import java.awt.Dimension;
//import java.awt.GridLayout;
//import java.sql.ResultSet;
import java.util.Hashtable;
import java.util.HashMap;
import java.util.Date;
/**
* FaultMgmt uses a custom TableModel.
*/
public class FaultMgmt extends JPanel implements ActionListener{
private boolean DEBUG = true;
final static boolean shouldFill = true;
final static boolean shouldWeightX = true;
final static boolean RIGHT_TO_LEFT = false;
JTable table;
FaultTableModel modal;
public void addComponentsToPane(Container pane) {

if (RIGHT_TO_LEFT) {
pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
}
JButton button;
JTextField txtTotal=new JTextField(5);
JLabel lblDisplaying=new JLabel("Displaying");
JTextField txtFrom=new JTextField(5);
JLabel lblTo=new JLabel("To");
JTextField txtTo=new JTextField(5);
JLabel lblPgLength=new JLabel("Page Length");
JComboBox cmbPaging=new JComboBox();
cmbPaging.addItem("25");
cmbPaging.addItem("50");
cmbPaging.addItem("75");
cmbPaging.addItem("100");
cmbPaging.addActionListener(this);

TableCellRenderer renderer = new CustomTableCellRenderer();
modal=new FaultTableModel();
table = new JTable(modal);
//table = new JTable(new FaultTableModel());
JTableHeader head =table.getTableHeader();
//head.setForeground( Color.BLUE);
head.setReorderingAllowed(false);//Cannot Rearrange the headers
//head.setResizingAllowed(false);//Cannot Resize Headers

//head.addMouseListener(modal.new ColumnListener(table));

//Setting the width of a particular Column
TableColumn colDesc = table.getColumnModel().getColumn(4);
colDesc.setMinWidth(50);
colDesc.setMaxWidth(250);
colDesc.setPreferredWidth(200);
//table.setShowGrid(false);//No Border
table.setRowHeight(30);
table.setOpaque(true);
//table.setSelectionBackground(Color.DARK_GRAY);
//table.setCellSelectionEnabled(false);
//table.setSelectionForeground(Color.RED);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent me) {
JTable table =(JTable) me.getSource();
Point p = me.getPoint();
int row = table.rowAtPoint(p);
int col = table.columnAtPoint(p);
if(me.getButton()==3){
//System.out.println("PRESSED BUTTON = "+me.getButton());
}

TableModel tableModel = (TableModel)table.getModel();
Object strValue = tableModel.getValueAt(row,0);
HashMap hmValues=new HashMap();

hmValues.put("FAULTID",tableModel.getValueAt(row,0));
hmValues.put("DATE",tableModel.getValueAt(row,1));
hmValues.put("SOURCE",tableModel.getValueAt(row,2));
hmValues.put("DESC",tableModel.getValueAt(row,3));
hmValues.put("COUNT",tableModel.getValueAt(row,4));
hmValues.put("ASSIGNEDTO",tableModel.getValueAt(row,5));
if (me.getClickCount() == 2) {
//System.out.println("Value is = "+strValue);
FaultDetails faultDetails=new FaultDetails(strValue.toString());
//FaultDetails faultDetails=new FaultDetails(hmValues);
//faultDetails.createAndShowGUI();
}
}
});
ListSelectionModel selectionModel = table.getSelectionModel();
//selectionModel.addListSelectionListener( this );

try{
//table.setDefaultRenderer( Class.forName( "java.lang.Integer" ), renderer );
table.setDefaultRenderer(Object.class, renderer );
}catch(Exception ee){
System.out.println(ee);
}

table.setPreferredScrollableViewportSize(new Dimension(500, 450));
//table.setPreferredScrollableViewportSize(new Dimension(400, 300));
//table.setForeground(Color.RED);

//Create the scroll pane and add the table to it.
JScrollPane scrollPane = new JScrollPane(table);

//System.out.println(table.getValueAt(0,5));

pane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();

c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(0,5,0,5);
pane.add(txtTotal, c);
c.gridx = 1;
c.gridy = 0;
pane.add(lblDisplaying, c);
c.gridx = 2;
c.gridy = 0;
pane.add(txtFrom, c);

c.gridx = 3;
c.gridy = 0;
pane.add(lblTo, c);

c.gridx = 5;
c.gridy = 0;
pane.add(txtTo, c);
c.gridx = 6;
c.gridy = 0;
pane.add(lblPgLength, c);
c.gridx = 7;
c.gridy = 0;
pane.add(cmbPaging, c);
c.gridx = 0;
c.gridy = 1;
c.gridwidth = 8;
c.insets = new Insets(10,0,10,0); //Top 10 and Bottom 10 padding
pane.add(scrollPane, c);
/*button = new JButton("Long-Named Button ddddddddd 4");
c.ipady = 20; //make this component tall
c.weighty = 0.0;
c.gridwidth = 1;
c.insets = new Insets(0,50,0,60); //left 50 and right 60 padding
c.gridx = 1;
c.gridy = 1;
c.fill = GridBagConstraints.NONE; //Check Commenting This Line.
pane.add(button, c);
button = new JButton("5");
c.ipady = 0; //reset to default
c.weighty = 1.0; //request any extra vertical space
c.anchor = GridBagConstraints.PAGE_END; //bottom of space
c.insets = new Insets(10,0,20,0); //top 10 and botton 20 padding
c.gridx = 1; //aligned with button 2
c.gridwidth = 2; //2 columns wide
c.gridy = 2; //third row
pane.add(button, c);
*/
}

/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Make sure we have nice window decorations.
JFrame.setDefaultLookAndFeelDecorated(true);
//Create and set up the window.
JFrame frame = new JFrame("NMS Fault Management Systemsss");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Set up the content pane.
//addComponentsToPane(frame.getContentPane());
frame.setResizable(false);
//Display the window.
frame.pack();
frame.setVisible(true);
}

public void actionPerformed(ActionEvent ae){
//Color c=new Color(255);
//System.out.println("Red= "+c.getRed()+" Green = "+c.getGreen()+" Blue = "+c.getBlue());
modal.set();
}
public static void main(String[] args) {
/*//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
*/
FaultMgmt fm = new FaultMgmt();
//Make sure we have nice window decorations.
JFrame.setDefaultLookAndFeelDecorated(true);

//Create and set up the window.
JFrame frame = new JFrame("NMS Fault Management Systems");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Set up the content pane.
fm.addComponentsToPane(frame.getContentPane());
frame.setResizable(false);
//Display the window.
frame.pack();
frame.setVisible(true);

}
}
Thanks.
 
Don Kiddick
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
IMHO. The best way to solve this problem is to create a new enumeration class "Severity", create a SeverityRenderer which renders colours in the table accordingly, then register your SeverityRenderer to render objects of classs "Severity". If you want to do it this way, I can help.
Alternatively if you want a quick "fix" to your problem, it is below. I also added shading to the coloured columns when they are selected - it looks better this way :

 
Mathews P Srampikal
Ranch Hand
Posts: 211
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hou!!!What a Quick.....Thanks
 
Mathews P Srampikal
Ranch Hand
Posts: 211
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Don,
Can u help in creating SeverityRenderer and Severity Class
 
Don Kiddick
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Ok. Lets start with the Severity class. This is going to be a typesafe enumeration with values Major, Minor, Information, Critical & Warning.
Typesafe enumeratinos are simple to write. Read item 21, have a go at writing the class, post the code and we can discuss.
D.
 
Mathews P Srampikal
Ranch Hand
Posts: 211
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Don I don't know C Still I have done something.See The code is it right???
import java.awt.Color;
public class Severity {

public static final Color MAJOR = Color.ORANGE;
public static final Color MINOR = Color.YELLOW;
public static final Color INFORMATION = Color.GREEN;
public static final Color CRITICAL = Color.RED;
public static final Color WARNING = Color.CYAN;
}
 
Don Kiddick
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Being able to write C is not really relevent. Being able to write enums in Java is. You're trying to write a class that represents the series {Major, Minor, Information, Critical & Warning}. Forget about colour for now. Read the doc and have another go, then we'll look at the solution.
D.
 
Mathews P Srampikal
Ranch Hand
Posts: 211
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You mean Object containing enum of the Same Objects like below
public class Severity {

public static final Severity MAJOR = new Severity();
public static final Severity MINOR = new Severity();
public static final Severity INFORMATION = new Severity();
public static final Severity CRITICAL = new Severity();
public static final Severity WARNING = new Severity();

private Severity(){
System.out.println("Privatre Constructor");
}
}
 
Don Kiddick
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Excellent stuff !
I have added some extra functionality which will be useful. In particular look at the static getSeverity method. This is how you will convert string values stored in the database into the corresponding Severity object.

Make sense ?
If so, try and write the SeverityRenderer class.
D.
 
Mathews P Srampikal
Ranch Hand
Posts: 211
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Is It???
import java.awt.Component;
//import java.awt.Color;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
//import javax.swing.table.TableCellRenderer;
//import javax.swing.table.TableCellEditor;
public class SeverityRenderer extends DefaultTableCellRenderer {

public SeverityRenderer(){
}
public Component getTableCellRendererComponent
(JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column) {
Component cell = super.getTableCellRendererComponent
(table, value, isSelected, hasFocus, row, column);

Severity svty=Severity.getSeverity(value.toString());
String strSvty=svty.toString();
//OR String strSvty=svty.getDescription();
return cell;
}
}//End of Class
 
Don Kiddick
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Your model is going to contain instances of type Severity ( in column 0 ). Your SeverityRenderer will render these objects. Try starting from this :

D.
 
Don Kiddick
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
ps. You have to write these bits :
//Decide what colour to paint the cell
//Colour the cell
 
Mathews P Srampikal
Ranch Hand
Posts: 211
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Don,
I have very urgently goto my place. see u after 2 days.Thanks for your help.I am sure i will do it after two days.Thanks,
 
Don Kiddick
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Shame, another 30mins and we're done.
Talk to you in two days.
D.
 
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I cannot restrict myself from adding a field of type Color to Severity. Then using an accessor for it, in the severity instance, makes trivial the decision about which color to render.
[ February 27, 2004: Message edited by: Jose Botella ]
 
Don Kiddick
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You could do that, but you would be putting rendering information in the model. On the plus side is slighty simpler than the solution I propose.
We will be creating a Map of Severity -> Color in our SeverityRenderer class. This also makes it trivial to decide what colour to render each cell.
D.
[ February 28, 2004: Message edited by: Don Kiddick ]
 
Mathews P Srampikal
Ranch Hand
Posts: 211
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Don Am Back.I was not well last 10 days.that's why i could not reply.Still i am not feeling well.Sorry for that.So let us continue.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic