Column Compare
Hi all
i wanted 2 retrive Data from Four tables,
i have Common Column in 3 tables i.e, from TEST,TEST1, TEST2
but I DONT HAVE COMMON COLUMN IN
table TEST & TEST3,
but i have Common Column in TEST2 & TEST3
CAN I WRITE THE SQL query as Below
select A.*,B.xyz1,
C.xyz2,
D.xyz3
from
TEST A,
TEST1 B,
TEST2 C,
TEST3 D
WHERE A.reason=B.reason
and
(A.reason1=C.reason1 and C.reason2=D.reason2)
please Suggest
many thanks
Duplicate post Column Compare in Query
Similar Messages
-
How to retrieve latest date column comparing with rest of the date columns ??
Hi Friends,
I have 6 Date columns (some of col has Null data) I need to compare all 6 columns date, how can I produce recent date to
new Column! can you please help me Tsql Code or Function.
Thanks for advance.Hej
create table datetest(id int,date1 datetime,date2 datetime,date3 datetime,date4 datetime)
insert into datetest values(1,GETDATE(),GETDATE()-1,GETDATE()-2,GETDATE()-3)
go
SELECT MAX(date_columns) AS max_dateFROM ( (SELECT date1 AS date_columns FROM datetest ) UNION ( SELECT date2 AS date_columns FROM datetest ) UNION ( SELECT date3 AS date_columns FROM datetest ) UNION ( SELECT date4 AS date_columns FROM datetest ) ) AS date_query -
Hi
Using below sql get the columns discrepncy .I want to display the discprency of columns from two tables in form of flat file using pl/sql.
select col1,col2 from A
minus
select * from B -- Rows in A that are not in B
union all
select col1,col2 from B
minus
select col1,col2 from A ----- rows in B that are not in A
Thanksin advance
MRHi
Wrote the cursor for this ,I am not getting expected o/p .Please any help
DECLARE
CURSOR C1 IS SELECT ACCOUNT_CUST_CD , account_contact_person_cd
FROM account where ACCOUNT_CUST_CD='1-411FQ'
AND account_contact_person_cd IS NOT NULL ORDER BY account_contact_person_cd ;
CURSOR C2 IS SELECT ACCOUNT_CUST_CD , account_contact_person_cd FROM bill_bkp
where ACCOUNT_CUST_CD='1-411FQ'AND ACCOUNT_STATUS_DESC='Blacklisted Customer'ORDER BY account_contact_person_cd ;
BEGIN
FOR REC1 IN C1
LOOP
FOR REC2 IN C2
LOOP
IF REC1.account_contact_person_cd <> REC2.account_contact_person_cd or
REC1.ACCOUNT_CUST_CD<>REC2.ACCOUNT_CUST_CD
THEN
DBMS_OUTPUT.PUT_LINE(REC1.account_contact_person_cd||REC2.account_contact_person_cd||REC1.ACCOUNT_CUST_CD||REC2.ACCOUNT_CUST_CD);
END IF;
END LOOP;
END LOOP;
END;
Thanks and Regards,
MR -
Hi all
I have four tables test1, test2 ,test3 & test4
i have Unique Common columns in test1, test2 ,test3
but i dont have common Column in test1, test4
But i have Uniqe Common Column in test3 & test4
Can i Write the Sql Query as Follows
please Suggest Me
I am in a Urgent Need
select A.*,B.xyz1,
C.xyz2,
D.xyz3
from
TEST1 A,
TEST2 B,
TEST3 C,
TEST4 D
WHERE
A.reason=B.reason
and
(A.reason1=C.reason1 and C.reason2=D.reason2)
many thanks
Edited by: jrDba - atm on Jun 7, 2009 1:36 AM
Edited by: jrDba - atm on Jun 7, 2009 3:35 AMI AM IN AN URGENT NEED1. Posting in upper case implies shouting. Don't shout, it won't get you any more (positive) attention.
2. Urgent implies that your need is greater than others. That is simply rude and, generally speaking, unnacceptable in forum nettiquette. Do a quick search on the word urgent in this forum and have a look at the kind of attention that it tends to get.
3. If you truly do have an urgent requiremnt, post a working test case i.e. create table and insert statements that will generate a set of data that represents the situation that you find yourself in. Also post expected results based on the sample data that you have supplied, along with a brief text description of your requirements. (Oh, and please try to use better names than Test1, test2 etc.)
Can i Write the Sql Query as FollowsWell, it's syntactically correct so, yes you can. However, since we have absolutely no idea what your requirements are, we can't say if it will give you what you need. -
Adding a column to a form in a meeting list
Hi -
I have a meeting list/calendar where I would like to add a column to the form that you get when you click to add a new meeting. I have created the column already, but can't figure out how to make it appear in the pop up form. I'm pretty new at
all this, so I'm guessing I'm missing something simple? I can add the column in other views, but I can't seem to get it to show up when you click the "add" button.
Thanks,
AmyHi Amy,
Open the ‘Event’ content type, and click your column under ‘Columns’ section, then click ‘Remove’ to remove it from the form. After that, re-add the column into the ‘Event’ content type through clicking ‘Add from existing site or list columns’, compare
the result.
Please create a new column, and on the ‘Additional Column Settings’ section, select ‘Add to all content types’, test again, then compare the result.
If this issue still exists , please create a new calendar, compare the result.
I hope this helps.
Thanks,
Wendy
Wendy Li
TechNet Community Support -
Conflict resolution for a table with LOB column ...
Hi,
I was hoping for some guidance or advice on how to handle conflict resolution for a table with a LOB column.
Basically, I had intended to handle the conflict resolution using the MAXIMUM prebuilt update conflict handler. I also store
the 'update' transaction time in the same table and was planning to use this as the resolution column to resolve the conflict.
I see however these prebuilt conflict handlers do not support LOB columns. I assume therefore I need to code a customer handler
to do this for me. I'm not sure exactly what my custom handler needs to do though! Any guidance or links to similar examples would
be very much appreciated.Hi,
I have been unable to make any progress on this issue. I have made use of prebuilt update handlers with no problems
before but I just don't know how to resolve these conflicts for LOB columns using custom handlers. I have some questions
which I hope make sense and are relevant:
1.Does an apply process detect update conflicts on LOB columns?
2.If I need to create a custom update/error handler to resolve this, should I create a prebuilt update handler for non-LOB columns
in the table and then a separate one for the LOB columns OR is it best just to code a single custom handler for ALL columns?
3.In my custom handler, I assume I will need to use the resolution column to decide whether or not to resolve the conflict in favour of the LCR
but how do I compare the new value in the LCR with that in the destination database? I mean how do I access the current value in the destination
database from the custom handler?
4.Finally, if I need to resolve in favour of the LCR, do I need to call something specific for LOB related columns compared to non-LOB columns?
Any help with these would be very much appreciated or even if someone can direct me to documentation or other links that would be good too.
Thanks again. -
JTable column Class (getColumnClass)
I create table model extended it from AbstractTableModel.
by overwriting getColumnClass in model.
@SuppressWarnings("unchecked")
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}but I have problem with TableRowSorter. I implement my own Comparator interface for TableRowSorter, Which
can compare column with Number and String or Boolean and String etc. ( String("") in cell with Number sense cells NULL value )
I passing my comparator to
TableRowSorter.setComparator(column, comparator);I have some number of comprators for String,Number and Boolean comparision.
If i call sorting of column with Number values
and columns first cell (0,0) contain String("") ( NULL value )
my code logic automatically set
TableRowSorter.setComparator(0, new StringComparator());but really column contains Number values with one String("") value.
right code must be
TableRowSorter.setComparator(0, new NumberComparator());how to determine column Class in right way???thanks everyone !!! I find solution :) I must create global Comparator for Object type and merge all different type comparators in to one ObjectComparator
-
TableSorter errors when adding new data
so here is the deal:
I am using the TableSorter.java helper class with DefaultTableModel
from: http://java.sun.com/docs/books/tutorial/uiswing/components/table.html
It works great when the data is static and I get it for the first time. however, occationally, when adding new data I get a NullPointerException error.
in use:
DefaultTableModel.addRow()
DefaultTableModel.removeRow() and
DefaultTableModel.insertRow() methods.
Error:
java.lang.ArrayIndexOutOfBoundsException: 5
at com.shared.model.TableSorter.modelIndex(TableSorter.java:294)
at com.shared.model.TableSorter.getValueAt(TableSorter.java:340)
at javax.swing.JTable.getValueAt(Unknown Source)
at javax.swing.JTable.prepareRenderer(Unknown Source)...
code problem I:
public Object getValueAt(int row, int column)
return tableModel.getValueAt(modelIndex(row), column);
}code problem II:
public int modelIndex(int viewIndex)
return getViewToModel()[viewIndex].modelIndex;
}TableSroter class:
package com.shared.model;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.List;
import javax.swing.*;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.*;
* 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
public class TableSorter extends AbstractTableModel
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 columnComparators = new HashMap();
private List sortingColumns = new ArrayList();
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, just pass the event along.
if (!isSorting())
clearSortingState();
fireTableChanged(e);
return;
// If the table structure has changed, cancel the sorting; the
// sorting columns may have been either moved or deleted from
// the model.
if (e.getFirstRow() == TableModelEvent.HEADER_ROW)
cancelSorting();
fireTableChanged(e);
return;
// We can map a cell event through to the view without widening
// when the following conditions apply:
// a) all the changes are on one row (e.getFirstRow() == e.getLastRow()) and,
// b) all the changes are in one column (column != TableModelEvent.ALL_COLUMNS) and,
// c) we are not sorting on that column (getSortingStatus(column) == NOT_SORTED) and,
// d) a reverse lookup will not trigger a sort (modelToView != null)
// Note: INSERT and DELETE events fail this test as they have column == ALL_COLUMNS.
// The last check, for (modelToView != null) is to see if modelToView
// is already allocated. If we don't do this check; sorting can become
// a performance bottleneck for applications where cells
// change rapidly in different parts of the table. If cells
// change alternately in the sorting column and then outside of
// it this class can end up re-sorting on alternate cell updates -
// which can be a performance problem for large tables. The last
// clause avoids this problem.
int column = e.getColumn();
if (e.getFirstRow() == e.getLastRow()
&& column != TableModelEvent.ALL_COLUMNS
&& getSortingStatus(column) == NOT_SORTED
&& modelToView != null)
int viewIndex = getModelToView()[e.getFirstRow()];
fireTableChanged(new TableModelEvent(TableSorter.this,
viewIndex, viewIndex,
column, e.getType()));
return;
// Something has happened to the data that may have invalidated the row order.
clearSortingState();
fireTableDataChanged();
return;
private class MouseHandler extends MouseAdapter
public void mouseClicked(MouseEvent e)
JTableHeader h = (JTableHeader) e.getSource();
TableColumnModel columnModel = h.getColumnModel();
int viewColumn = columnModel.getColumnIndexAtX(e.getX());
int column = columnModel.getColumn(viewColumn).getModelIndex();
if (column != -1)
int status = getSortingStatus(column);
if (!e.isControlDown())
cancelSorting();
// Cycle the sorting states through {NOT_SORTED, ASCENDING, DESCENDING} or
// {NOT_SORTED, DESCENDING, ASCENDING} depending on whether shift is pressed.
status = status + (e.isShiftDown() ? -1 : 1);
status = (status + 4) % 3 - 1; // signed mod, returning {-1, 0, 1}
setSortingStatus(column, status);
private static class Arrow implements Icon
private boolean descending;
private int size;
private int priority;
public Arrow(boolean descending, int size, int priority)
this.descending = descending;
this.size = size;
this.priority = priority;
public void paintIcon(Component c, Graphics g, int x, int y)
Color color = c == null ? Color.GRAY : c.getBackground();
// In a compound sort, make each succesive triangle 20%
// smaller than the previous one.
int dx = (int)(size/2*Math.pow(0.8, priority));
int dy = descending ? dx : -dx;
// Align icon (roughly) with font baseline.
y = y + 5*size/6 + (descending ? -dy : 0);
int shift = descending ? 1 : -1;
g.translate(x, y);
// Right diagonal.
g.setColor(color.darker());
g.drawLine(dx / 2, dy, 0, 0);
g.drawLine(dx / 2, dy + shift, 0, shift);
// Left diagonal.
g.setColor(color.brighter());
g.drawLine(dx / 2, dy, dx, 0);
g.drawLine(dx / 2, dy + shift, dx, shift);
// Horizontal line.
if (descending) {
g.setColor(color.darker().darker());
} else {
g.setColor(color.brighter().brighter());
g.drawLine(dx, 0, 0, 0);
g.setColor(color);
g.translate(-x, -y);
public int getIconWidth()
return size;
public int getIconHeight()
return size;
private class SortableHeaderRenderer implements TableCellRenderer
private TableCellRenderer tableCellRenderer;
public SortableHeaderRenderer(TableCellRenderer tableCellRenderer)
this.tableCellRenderer = tableCellRenderer;
public Component getTableCellRendererComponent(JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column)
Component c = tableCellRenderer.getTableCellRendererComponent(table,
value, isSelected, hasFocus, row, column);
if (c instanceof JLabel) {
JLabel l = (JLabel) c;
l.setHorizontalTextPosition(JLabel.LEFT);
int modelColumn = table.convertColumnIndexToModel(column);
l.setIcon(getHeaderRendererIcon(modelColumn, l.getFont().getSize()));
return c;
private static class Directive
private int column;
private int direction;
public Directive(int column, int direction)
this.column = column;
this.direction = direction;
}any input will be appreciated.
thanks
PeterThe code you posted doesn't help us at all. Its just a duplicate of the code from the tutorial. The custom code is what you have written. For example do you update the TableModel from the Event Thread? Do you update the SortModel or the DefaultTableModel? If you actually provide your test code and somebody has already downloaded the sort classes, then maybe they will test your code against the classes. But I doubt if people will download the sort classes and create a test program just to see if they can duplicate your results (at least I know I'm not about to).
-
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 -
JTable sorting - problem when adding elements (complete code inside)
I�m writing this email with reference to a recent posting here but this time with the code example. (I apologize for the duplicated posting � this time it will be with the code)
Problem: when adding more elements to the JTable (sorted) the exception: ArrayIndexOutOfBoundsException is thrown.
Example: If the elements in the table are 10 and then the user requests for 8 � the table will produce the correct result. However, if the user will ask for 11 items (>10) the exception will be thrown.
The program: The program below (compiles and running). A JTable is constructed with 3 items, when you click the button - the return result should be 4 items - this will generate the error, WHY?
I would highly appreciate your thoughts why this is happening and most importantly � how to fix it.
Thanks a lot
3 files:
(1) TableSorterDemo
(2) Traveler
(3)TableSorter
//TableSorterDemo:
package sorter;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
* TableSorterDemo is like TableDemo, except that it
* inserts a custom model -- a sorter -- between the table
* and its data model. It also has column tool tips.
public class TableSorterDemo implements ActionListener
private JPanel superPanel;
private JButton clickMe = new JButton("click me to get diff data");
private boolean DEBUG = false;
private DefaultListModel defaultListModel;
private JTable table;
public TableSorterDemo()
superPanel = new JPanel(new BorderLayout());
defaultListModel = new DefaultListModel();
init1();
TableSorter sorter = new TableSorter(new MyTableModel(defaultListModel)); //ADDED THIS
table = new JTable(sorter); //NEW
sorter.setTableHeader(table.getTableHeader()); //ADDED THIS
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
//Set up tool tips for column headers.
table.getTableHeader().setToolTipText(
"Click to specify sorting; Control-Click to specify secondary sorting");
//Create the scroll pane and add the table to it.
JScrollPane scrollPane = new JScrollPane(table);
//Add the scroll pane to this panel.
superPanel.add("Center", scrollPane);
superPanel.add("South",clickMe);
clickMe.addActionListener(this);
public JPanel getPanel()
return superPanel;
public void init1()
//in real life this will be done from the db
Traveler a = new Traveler();
Traveler b = new Traveler();
Traveler c = new Traveler();
a.setFirstName("Elvis");
a.setLastName("Presley");
a.setSprot("Ping Pong");
a.setNumYears(3);
a.setVegetarian(true);
b.setFirstName("Elton");
b.setLastName("John");
b.setSprot("Soccer");
b.setNumYears(2);
b.setVegetarian(true);
c.setFirstName("shaquille");
c.setLastName("oneil");
c.setSprot("Golf");
c.setNumYears(22);
c.setVegetarian(true);
defaultListModel.addElement(a);
defaultListModel.addElement(b);
defaultListModel.addElement(c);
public void init2()
//in real life this will be done from the db
Traveler d = new Traveler();
Traveler e = new Traveler();
Traveler f = new Traveler();
Traveler g = new Traveler();
d.setFirstName("John");
d.setLastName("Smith");
d.setSprot("Tennis");
d.setNumYears(32);
d.setVegetarian(true);
e.setFirstName("Ron");
e.setLastName("Cohen");
e.setSprot("Baseball");
e.setNumYears(12);
e.setVegetarian(true);
f.setFirstName("Donald");
f.setLastName("Mac Novice");
f.setSprot("Vallyball");
f.setNumYears(1);
f.setVegetarian(true);
g.setFirstName("Eithan");
g.setLastName("Superstar");
g.setSprot("Vallyball");
g.setNumYears(21);
g.setVegetarian(true);
defaultListModel.addElement(d);
defaultListModel.addElement(e);
defaultListModel.addElement(f);
defaultListModel.addElement(g);
class MyTableModel extends AbstractTableModel
private DefaultListModel myModel;
public MyTableModel(DefaultListModel m)
myModel=m;
private String[] columnNames = {"First Name",
"Last Name",
"Sport",
"# of Years",
"Vegetarian"};
public int getColumnCount()
return columnNames.length;
public int getRowCount()
return myModel.size();
public String getColumnName(int column)
return getNames()[column];
public String[] getNames()
String[] names = {"First Name", "Last Name", "Sport", "# of Years", "Vegetarian"};
return names;
public Object getValueAt(int row, int col)
return distributeObjectsInTable(row, col, (Traveler) myModel.elementAt(row));
public Object distributeObjectsInTable(int row, int col, Traveler tr)
switch(col)
case 0:
return tr.getFirstName();
case 1:
return tr.getLastName();
case 2:
return tr.getSprot();
case 3:
return new Integer(tr.getNumYears());
case 4:
return new Boolean (tr.isVegetarian());
default:
return "Error";
public Class getColumnClass(int c)
return getValueAt(0, c).getClass();
private static void createAndShowGUI()
//Make sure we have nice window decorations.
JFrame.setDefaultLookAndFeelDecorated(true);
//Create and set up the window.
JFrame frame = new JFrame("TableSorterDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
TableSorterDemo newContentPane = new TableSorterDemo();
newContentPane.getPanel().setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane.getPanel());
//Display the window.
frame.pack();
frame.setVisible(true);
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();
public void actionPerformed(ActionEvent ae)
if (ae.getSource()==clickMe)
defaultListModel.removeAllElements();
init2(); //if the size of the model was less than 2 items - the result will be ok.
//in other words, if you commens the last 2 rows of this method (addElement(f) & g)
// the result will be fine.
table.updateUI();
}//(2) Traveler
package sorter;
public class Traveler
private String firstName;
private String lastName;
private String sprot;
private int numYears;
private boolean vegetarian;
public String getFirstName()
return firstName;
public String getLastName()
return lastName;
public int getNumYears()
return numYears;
public String getSprot()
return sprot;
public boolean isVegetarian()
return vegetarian;
public void setFirstName(String firstName)
this.firstName = firstName;
public void setLastName(String lastName)
this.lastName = lastName;
public void setNumYears(int numYears)
this.numYears = numYears;
public void setSprot(String sprot)
this.sprot = sprot;
public void setVegetarian(boolean vegetarian)
this.vegetarian = vegetarian;
}//(3)TableSorter
package sorter;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.List;
import javax.swing.*;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.*;
public class TableSorter extends AbstractTableModel {
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 columnComparators = new HashMap();
private List sortingColumns = new ArrayList();
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, just pass the event along.
if (!isSorting()) {
clearSortingState();
fireTableChanged(e);
return;
// If the table structure has changed, cancel the sorting; the
// sorting columns may have been either moved or deleted from
// the model.
if (e.getFirstRow() == TableModelEvent.HEADER_ROW) {
cancelSorting();
fireTableChanged(e);
return;
// We can map a cell event through to the view without widening
// when the following conditions apply:
// a) all the changes are on one row (e.getFirstRow() == e.getLastRow()) and,
// b) all the changes are in one column (column != TableModelEvent.ALL_COLUMNS) and,
// c) we are not sorting on that column (getSortingStatus(column) == NOT_SORTED) and,
// d) a reverse lookup will not trigger a sort (modelToView != null)
// Note: INSERT and DELETE events fail this test as they have column == ALL_COLUMNS.
// The last check, for (modelToView != null) is to see if modelToView
// is already allocated. If we don't do this check; sorting can become
// a performance bottleneck for applications where cells
// change rapidly in different parts of the table. If cells
// change alternately in the sorting column and then outside of
// it this class can end up re-sorting on alternate cell updates -
// which can be a performance problem for large tables. The last
// clause avoids this problem.
int column = e.getColumn();
if (e.getFirstRow() == e.getLastRow()
&& column != TableModelEvent.ALL_COLUMNS
&& getSortingStatus(column) == NOT_SORTED
&& modelToView != null) {
int viewIndex = getModelToView()[e.getFirstRow()];
fireTableChanged(new TableModelEvent(TableSorter.this,
viewIndex, viewIndex,
column, e.getType()));
return;
// Something has happened to the data that may have invalidated the row order.
clearSortingState();
fireTableDataChanged();
return;
private class MouseHandler extends MouseAdapter {
public void mouseClicked(MouseEvent e) {
JTableHeader h = (JTableHeader) e.getSource();
TableColumnModel columnModel = h.getColumnModel();
int viewColumn = columnModel.getColumnIndexAtX(e.getX());
int column = columnModel.getColumn(viewColumn).getModelIndex();
if (column != -1) {
int status = getSortingStatus(column);
if (!e.isControlDown()) {
cancelSorting();
// Cycle the sorting states through {NOT_SORTED, ASCENDING, DESCENDING} or
// {NOT_SORTED, DESCENDING, ASCENDING} depending on whether shift is pressed.
status = status + (e.isShiftDown() ? -1 : 1);
status = (status + 4) % 3 - 1; // signed mod, returning {-1, 0, 1}
setSortingStatus(column, status);
private static class Arrow implements Icon {
private boolean descending;
private int size;
private int priority;
public Arrow(boolean descending, int size, int priority) {
this.descending = descending;
this.size = size;
this.priority = priority;
public void paintIcon(Component c, Graphics g, int x, int y) {
Color color = c == null ? Color.GRAY : c.getBackground();
// In a compound sort, make each succesive triangle 20%
// smaller than the previous one.
int dx = (int)(size/2*Math.pow(0.8, priority));
int dy = descending ? dx : -dx;
// Align icon (roughly) with font baseline.
y = y + 5*size/6 + (descending ? -dy : 0);
int shift = descending ? 1 : -1;
g.translate(x, y);
// Right diagonal.
g.setColor(color.darker());
g.drawLine(dx / 2, dy, 0, 0);
g.drawLine(dx / 2, dy + shift, 0, shift);
// Left diagonal.
g.setColor(color.brighter());
g.drawLine(dx / 2, dy, dx, 0);
g.drawLine(dx / 2, dy + shift, dx, shift);
// Horizontal line.
if (descending) {
g.setColor(color.darker().darker());
} else {
g.setColor(color.brighter().brighter());
g.drawLine(dx, 0, 0, 0);
g.setColor(color);
g.translate(-x, -y);
public int getIconWidth() {
return size;
public int getIconHeight() {
return size;
private class SortableHeaderRenderer implements TableCellRenderer {
private TableCellRenderer tableCellRenderer;
public SortableHeaderRenderer(TableCellRenderer tableCellRenderer) {
this.tableCellRenderer = tableCellRenderer;
public Component getTableCellRendererComponent(JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column) {
Component c = tableCellRenderer.getTableCellRendererComponent(table,
value, isSelected, hasFocus, row, column);
if (c instanceof JLabel) {
JLabel l = (JLabel) c;
l.setHorizontalTextPosition(JLabel.LEFT);
int modelColumn = table.convertColumnIndexToModel(column);
l.setIcon(getHeaderRendererIcon(modelColumn, l.getFont().getSize()));
return c;
private static class Directive {
private int column;
private int direction;
public Directive(int column, int direction) {
this.column = column;
this.direction = direction;
}The table listens to the TableModel for changes. Changing the table by adding/removing
rows or columns has no affect on its table model. If you make changes to the table model
the table will be notified by its TableModelListener and change its view. So tell
MyTableModel about the change of data:
public class TableSorterDemo implements ActionListener
MyTableModel tableModel;
public TableSorterDemo()
defaultListModel = new DefaultListModel();
init1();
tableModel = new MyTableModel(defaultListModel);
TableSorter sorter = new TableSorter(tableModel);
public void actionPerformed(ActionEvent ae)
if (ae.getSource()==clickMe)
defaultListModel.removeAllElements();
init2();
tableModel.fireTableStructureChanged();
} -
Warning messages (Moving from JDK1.4 to DJK1.5)
I got some warning messages after I moved from 1.4 to 1.5, can someone show me the right way to avoid them ?
=====================================================================
Scanner.java:909: warning: [unchecked] unchecked call to add(E) as a member of the raw type java.util.Vector
Region[Region_Id].add(region_element);
In my code :
region_element=new Region_Element();
static Vector Region[]=new Vector[64];
I tied :
static Vector<Region_Element> Region[]=new Vector<Region_Element>[64];
but still got warning message.
=====================================================================
Set_Maker.java:31: warning: [unchecked] unchecked cast
found : java.lang.Object
required: java.util.TreeSet<java.lang.Object>
try { S1=(TreeSet<Object>)o1; }
In my code :
static final Comparator<Object> TreeSet_Order=new Comparator<Object>()
public int compare(Object o1,Object o2)
if (Debug) System.out.println("=00= o1="+o1+" o2="+o2);
TreeSet<Object> S1=new TreeSet<Object>(TreeSet_Order);
TreeSet<Object> S2=new TreeSet<Object>(TreeSet_Order);
try { S1=(TreeSet<Object>)o1; } // Line 31
catch (ClassCastException e) { S1.add(o1); }
==================================================================
JDBCAdapter.java:190: warning: [unchecked] unchecked call to setElementAt(E,int) as a member of the raw type java.util.Vector
dataRow.setElementAt(value, column);
In my code :
Vector rows=new Vector();
public void setValueAt(Object value,int row,int column)
Vector dataRow=(Vector)rows.elementAt(row);
dataRow.setElementAt(value, column); // Line 190
=================================================================
TableSorter.java:60: warning: [unchecked] unchecked call to compareTo(T) as a member of the raw type java.lang.Comparable
public int compare(Object o1, Object o2) { return ((Comparable) o1).compareTo(o2); }
In my code :
public static final Comparator COMPARABLE_COMAPRATOR = new Comparator()
public int compare(Object o1, Object o2) { return ((Comparable) o1).compareTo(o2); } // Line 60
==================================================================
TableSorter.java:260: warning: [unchecked] unchecked call to compare(T,T) as a member of the raw type java.util.Comparator
else { comparison = getComparator(column).compare(o1, o2); }
In my code :
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;
Object o1 = tableModel.getValueAt(row1, column);
Object o2 = tableModel.getValueAt(row2, column);
else { comparison = getComparator(column).compare(o1, o2); } // Line 260I have tried so many ways but I can't seem to get rid of the warning on this matter. I have no idea how to use the generics on Vector. The other part of Generics I can undertand but just this. In my case I am adding multiple types of datatype and how am I supposed just say if it is supposed to be
<String> or <Interger>or a
<Double>. I even tried using the Wildcard
<?>. Still no effect on it. Earlier I was trying it out with a Cosole program so I just revised the Version back to 1.4 SDK but now I am implementing a GUI to the program and I am in a real need to know how to solve it since I have to use the 1.5 JDK. Please Help me. I can't even find an example out there which uses Generic type methods to add to the Vector using the getter and setter method. Could there be a problem with the getter or setter of the program? -
Error in select - dynamic table
HI
Im creating a dynamic internal table and fetching values and displaying.
select * from (p_table) into corresponding fields of table <dyn_table>.
This statement works well for small tables as PRHI , PRPS , PROJ etc
when i trying exceuting the same for EKKO,BSEG and other bigger tables it gives short dump whereas small tables it works fine.
Why is this happening
can you suggest some way to rectify it ?
Thanks in advance
SwarnaWhen i debug im getting the fields in my dynamic internal table for all tables.
Also only for tables with lots of columns asLIPS, EKKO ,EKPO it is throwing error.
The same code works fine for tables like t001,t005,prhi,prps,proj tables which have a fewer columns compared to the previous mentioned tables.
Is there any fix on the max number of columns ? -
I use TableSorter from java web and when I run it gave me these warning. How can I fix this thank heaps.
C:\Project>javac -Xlint *.java
TableSorter.java:76: warning: [unchecked] unchecked call to compareTo(T) as a member of the raw type java.lang.Comparable
return ((Comparable) o1).compareTo(o2);
^
TableSorter.java:185: warning: [unchecked] unchecked call to add(E) as a member of the raw type java.util.List
sortingColumns.add(new Directive(column, status));
^
TableSorter.java:207: warning: [unchecked] unchecked call to put(K,V) as a member of the raw type java.util.Map
columnComparators.put(type, comparator);
^
TableSorter.java:312: warning: [unchecked] unchecked call to compare(T,T) as a member of the raw type java.util.Comparator
comparison = getComparator(column).compare(o1, o2);
^
4 warnings
Appreciate
LoveI am still relatively new to java and have a similar issue. I wanted to leverage Vector to create a self-sorting list (imposing a specific object type in the process).
public class FooList extends Vector {
public boolean add(FooNode node){
boolean result = true;
int iInsertionPoint = 0, iListLength = 0;
iListLength = this.size();
switch(MyIndexType){
case IndexByDouble:
iInsertionPoint = find(node.lfKey);
break;
case IndexByLongInt:
iInsertionPoint = find(node.iKey);
break;
case IndexByString:
iInsertionPoint = find(node.sKey);
break;
default:
result = false;
} // switch
if(iInsertionPoint >= iListLength)
addElement(node);
else
add(iInsertionPoint, node);
return result;
} // FooList.add()
} // class FooListthe two add calls are methods inherited from Vector and produce the following warnings:
Compiling 1 source file to ...\build\classes
...\util\FooList.java:75: warning: [unchecked] unchecked call to addElement(E) as a member of the raw type java.util.Vector
addElement(node);
...\util\FooList.java:77: warning: [unchecked] unchecked call to add(int,E) as a member of the raw type java.util.Vector
add(iInsertionPoint, node);
2 warningsEspecially with my novice status, I really dislike warnings. Can anyone provide any suggestions on how to do this better or at least eliminate the warnings? -
I am looking for only column compare for making my target table same as source table.
My query:
select case when column_name_s is null and column_name_t is not null
then 'alter table GRADE_CONVERSION drop ' || column_name_t || ';'
when column_name_s is not null and column_name_t is null
then 'alter table GRADE_CONVERSION add ' || column_name_s || ' ' || data_type_s ||';'
else 'alter table GRADE_CONVERSION modify ' || column_name_t || ' ' || data_type_t ||';'
end alterations
from (select s.column_name column_name_s,t.column_name column_name_t,
s.data_type data_type_s,t.data_type data_type_t
from (select column_id,column_name,data_type
from all_tab_cols@database
where owner = 'erhan'
and table_name = 'GRADE_CONVERSION'
) s
full outer join
(select column_id,column_name,data_type
from all_tab_cols@database
where owner = 'sarigul'
and table_name = 'GRADE_CONVERSION'
) t
on s.column_name = t.column_name
Tables:
Target table: GRADE_CONVERSION table in sarigul@database
LETTER_GRADE
VARCHAR2(2)
GRADE_POINT
NUMBER(3,2)
MAX_GRADE
NUMBER(3)
MIN_GRADE
NUMBER(3)
Source table: GRADE_CONVERSION table in erhan@database
LETTER_GRADE
VARCHAR2(2)
GRADE_POINT
NUMBER(3,2)
MAX_GRADE
NUMBER(3)
MIN_GRADE
NUMBER(3)
CREATED_BY
VARCHAR2(30)
CREATED_DATE
DATE
MODIFIED_BY
VARCHAR2(30)
MODIFIED_DATE
DATE
want to see the result similar to this *(please ignore the column names here this is just a plain exemple:)
Alter table Target_table modify BOOK_ID Varchar2 (4);
Alter table Target_table add ISBN_10 Varchar2(13), null;
Alter table Target_table drop TITLE;I am looking for only column compare for making my target table same as source table.
My query:
select case when column_name_s is null and column_name_t is not null
then 'alter table GRADE_CONVERSION drop ' || column_name_t || ';'
when column_name_s is not null and column_name_t is null
then 'alter table GRADE_CONVERSION add ' || column_name_s || ' ' || data_type_s ||';'
else 'alter table GRADE_CONVERSION modify ' || column_name_t || ' ' || data_type_t ||';'
end alterations
from (select s.column_name column_name_s,t.column_name column_name_t,
s.data_type data_type_s,t.data_type data_type_t
from (select column_id,column_name,data_type
from all_tab_cols@database
where owner = 'erhan'
and table_name = 'GRADE_CONVERSION'
) s
full outer join
(select column_id,column_name,data_type
from all_tab_cols@database
where owner = 'sarigul'
and table_name = 'GRADE_CONVERSION'
) t
on s.column_name = t.column_name
Tables:
Target table: GRADE_CONVERSION table in sarigul@database
LETTER_GRADE
VARCHAR2(2)
GRADE_POINT
NUMBER(3,2)
MAX_GRADE
NUMBER(3)
MIN_GRADE
NUMBER(3)
Source table: GRADE_CONVERSION table in erhan@database
LETTER_GRADE
VARCHAR2(2)
GRADE_POINT
NUMBER(3,2)
MAX_GRADE
NUMBER(3)
MIN_GRADE
NUMBER(3)
CREATED_BY
VARCHAR2(30)
CREATED_DATE
DATE
MODIFIED_BY
VARCHAR2(30)
MODIFIED_DATE
DATE
want to see the result similar to this *(please ignore the column names here this is just a plain exemple:)
Alter table Target_table modify BOOK_ID Varchar2 (4);
Alter table Target_table add ISBN_10 Varchar2(13), null;
Alter table Target_table drop TITLE; -
Why is it that if say a deriv is dealt with followed by another deriv the second is missed? why is the order of the term important for this code to work?
public void removeIdenticalTerms(String [][] goldStandard, String [][] testModel, int numRows, int goldRows, int columns)
* Compare all terms in the goldStandard with those in testModel,
* if any are found remove them and shuffleUp
* This should also remove any deriv operators
* Then call the next method
int difference=0;
for(int i=0; i<goldRows; i++)
for(int k=0; k<numRows; k++)
if(goldStandard[0].equals(testModel[k][0]))
//The predicates match so compare the variables
if((goldStandard[i][0].equals("deriv"))||(goldStandard[i][0].equals("m_plus"))||(goldStandard[i][0].equals("minus")))
if((goldStandard[i][1].equals(testModel[k][1]))&&(goldStandard[i][2].equals(testModel[k][2])))
System.out.println("\nA " + goldStandard[i][0] + " has been removed");
//Remove and shuffle up
for(int h=0; h<columns; h++)
goldStandard[i][h] = null;
testModel[k][h]=null;
shuffleUp(goldStandard, i, goldRows, columns);
goldRows--;
shuffleUp(testModel, k, numRows, columns);
numRows--;
else if(goldStandard[i][0].equals("add"))
if((goldStandard[i][1].equals(testModel[k][1]))&&(goldStandard[i][2].equals(testModel[k][2]))&&(goldStandard[i][3].equals(testModel[k][3])))
System.out.println("\nAn " + goldStandard[i][0] + " has been removed");
//Remove and shuffle up
for(int h=0; h<columns; h++)
goldStandard[i][h] = null;
testModel[k][h]=null;
shuffleUp(goldStandard, i, goldRows, columns);
goldRows--;
shuffleUp(testModel, k, numRows, columns);
numRows--;
System.out.println("\nTest Model\n");
for(int g=0; g<numRows; g++)
for(int m=0; m<columns; m++)
if(!(testModel[g][m]== null))
System.out.println(testModel[g][m]);
System.out.println("\nGold Standard\n");
for(int g=0; g<goldRows; g++)
for(int m=0; m<columns; m++)
if(!(goldStandard[g][m]==null))
System.out.println(goldStandard[g][m]);
countOperators(goldStandard, testModel, numRows, goldRows, columns);Well, here is another instance where I would use collections
(LinkedList or ArrayList).
But if you have to use arrays...
Well, I guess instead of removing all the ones you want to remove
and shuffling them all up, you could store the indeces that you find
then after collecting them all, run the remove and shuffle up for each
index found.
int[] removeThese = new int[goldRows]; //Maybe need to remove all rows!
int currentPlace = 0;
for (int i = //...) {
for (int k = //...) {
if (goldRows[ i ][ 0 ].equals(//...)//...) {
removeThese[currentPlace++] = i;
//Dont remove or shuffle yet
for (int r = 0; r <= currenPlace; r++) {
remove(goldRow, removeThese[r], //...);
shuffleUp(goldRow, removeThese[r], //...);
}As psuedo code...
Maybe you are looking for
-
First user(on ipad) is successful in logging in via Mobile Iron Secure Sign-In. First user logs out. Second user logs in. Second user is quarantined, shows not compliant. WLC and ISE shows first user instead of the Second user. To resolve this is
-
Dvd to appletv video not smooth
i downloaded the mac trial of dvd to apple tv and ripped a disk...the video is not smooth..it pauses every few seconds and makes it unwatchable... any one have any thoughts on this? i tried ripping on 2 different macs one powerpc and one intel help p
-
Triggering output type from VL02N
Hi, I need to attach some kind of routine to VL02n. The requirement is that in VL02N, on goods issue, an output type is supposed to be triggered. Please suggest me as to how to trigger this output type on goods issue. The functionality is like this..
-
Adding a new tab at a specific place
Hi, can someone help with a tab question. In earlier version of Indesign (CS6) you use to be able to use the 'enter' key to add a new tab at a specific measurement. Example: you start with a tab at 100mm, then you could type 125mm (in the x measureme
-
50G / simultaneous multiple scatter plots + intersection of linear regression lines
I have a real specific problem with scatter plots and linear regression lines. First, I've been looking over the manual and the internet trying to figure out how to graph multiple scatter plots at the same time, but it seems like you can only do Colu