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

Similar Messages

  • ITunes 8.2 displaying songs in wrong order

    Hi there
    Recently had Windows die on me, so I had to do a clean install of Windows Vista. I was not able to access any settings/libraries etc before the computer died.
    Fortunately I had just copied my MP3s onto an external drive a few days earlier. Have updated to SP2, all fixes applied etc. I've imported all the songs back into a new install of iTunes.
    I used to sort my songs via Album by Artist but when I do this now I find my compilations or those with "various artists" in the album by artist field will not display in the correct track order ie might go track 6, 3, 11, 1, 5, 7 etc .
    The songs are grouped together as an album, but not in the correct order. The track names aren't listed in alphabetical order - the order seems random for all the affected albums.
    I have tried editing the info and checked disc numbers, track numbers (including re-entering each number and making sure the total number of tracks is correct) , album names, genres etc. Group by compilation has been checked. Have tried part of compilation yes and no. Have made sure each field is exactly the same. No joy.
    If I sort by album the tracks display in the correct order but I want to sort Album By Artist - it's easier to browse through the library by artist rather than albums.
    Anyone got any suggestions? I would rather not have to change the Artist field for compilation albums to the same artist name just to get the tracks in the correct order.
    I have about 9000 songs and all of them were either imported from original CD albums or purchased from iTunes - no torrent music etc.
    Thanks for your help

    See my previous post on Grouping Tracks Into Albums, in particular the topics Use an album friendly view and Tracks out of sequence. (N.b. You can ignore the bit about Artist & Sort Artist being consistent for a compilation, but every track must have Part of a Compilation set to Yes).
    tt2

  • Photos are show in wrong order

    Hello,
    I bought an iPod Touch 32 GB because I thought it's a good way to carry my pictures with me.
    The problem is that within the folders/albums the pictures are displayed in the wrong order. It's not chronlogically, by name or something else I can identify.
    What have I done?
    I'm using a XP laptop and my pictures are stored in several folders on a NAS. First I made sure that the pictures were sorted by "picture taken on". Then I selected the picture folder in iTunes and selected several subfolders to be transferred to the iPod. It took a while as we are talking of 15.000 pictures. Some of the folders have 10 or 20 pictures, some of the folders have 200 or even 400 pictures. It's important for me that they will be displayed in a chronological or by name. But I have the feeling that starting from a certain amount of pictures (like 30 or 40) it completely destroys the structure.
    What can I do?
    I hope I was able to make my point as I'm writing you from Germany and my English is not the best.
    Please help me to get this problem solved.

    FOUND SOLUTION  from another unhappy guy (forgot his name) but he was very kind in posting the solution after he broke his brain trying with the Support team  (?)
    in any case here is the solution:
    1 - in PHOTOS   check sync
    2 - DO NOT SELECT ANY Folders or files
    3 - let the phone do the sync
    4 - repeat the sync by selecting the folders you intend to sync
    It did worked for me....try
    good luck
    PS - I wish that the board could be monitored by Apple experts so that they may add valid
    solutions to problems rather then us going crazy looking for intelligent reply to questions!

  • Track info changes reverting & wrong order. Soundcheck doesn't rescan.

    Looks like I've had less serious probs with iTunes 7 than a lot of people, but there are a few irritating bugs:
    1) On one album in my library, I keep changing the Album Artist, but it keeps changing itself back whenever the tracks are played. For some reason iTunes entered the Album Artist as "Soundtrack". I changed it to the real artist, and when each track is played it reverts back to "Soundtrack". I'm not even allowed to name my own library??
    2) Tracks from the same album are sometimes displayed in the wrong order, eg track 6 will appear before track 1. If I play track 1, track 6 moves down between tracks 1 & 2. Play track 2 & track 6 moves down another place. All tracks names/numbers etc have the same convention & all labelled N of N tracks etc. It also seems to have split some of my albums into different album artists (I've only ever used Artist, not album Artist) so I've had a huge amount of restoration work to do on my library.
    3) After upgrading, the Soundcheck tick disappeared from Preferences. When I re-check it, it doesn't re-scan anything, not even the tracks I added since the upgrade. Sound check doesn't even seem to be mentioned in the help file from what I can remember from when I tried this.
    4) Also having the same probs as other people with jumpy video playback & high CPU usage.
    5) New Cover view for Album covers is a nice touch, but no explanation on how it works (I understand it doesn't automatically add the artwork to the ID3 tags). Also, when I change to Browse by album cover, I just get a useless message saying that it's unable to browse by album cover on this computer. Help file is utterly useless & no solutions on internet. I suspect my DirectX/graphics card setup may be involved somewhere, but how come it's able to display album covers in the other two views?
    General consensus seems to be that this software release is a real shocker & although there seems to be a lot of hysteria over it on these forums, I can't believe it was released in this state. Apple need to pull their fingers out.

    Hi,
    Many thanks for the suggestions - replies as follows:
    1) I never have this option checked.
    2) This is when sorted by album - it's definitely not connected with my view settings.
    3) Cool - I was probably basing this on previous versions when I think think you could see Soundcheck running (if you couldn't I think you could scroll through the displays in the Now Playing window at the top). There was no apparent disk activity after checking either, but I haven't got arounud to checking file modified timestamps. Still don't understand why Soundcheck was disabled after upgrade though...
    4) This didn't happen with previous versions of iTunes. Have already scoured the web for help & it sounds like a common problem with this release. I built this PC!
    5) DirectX is already running on v9.0c, and I've got the latest drivers for my ATI Radeon 7500 128MB card. I thought it might be DirectX-related as I've been having problems getting Direct3D acceleration enabled. Haven't found any fixes yet relevant to this - have uninstalled all remote control software (including mirror drivers)& made a NetMeeting change which supposedly fixes this but no luck, reinstalled SP2, reinstalled drivers etc. Argh.
    Thanks for your help!

  • What's wrong with this code to display a JTable?

    Hi.
    I am trying to display a JTable in BorderLayout.CENTER, and I am getting this compile time error:
    SampleVIew.java:78: cannot resolve symbol
    method add (SampleView.NewTable)
    class javax.swing.JPanel
    .....guiPane.add(DefaultNewTable);
    Here is the code snippet, I've highlighted the offensive code with <--- HERE
    public class SampleView extends JApplet
      public SampleView()
        JFrame pf = new JFrame("Testing");
        Container content = pf.getContentPane();
        // ============================== CENTER
        JPanel centerPane = new JPanel(new GridLayout(2,0));
           // ============================== add new table to top half of centerPane
        NewTable DefaultNewTable = new NewTable();
        JScrollPane scrollpane = new JScrollPane(DefaultNewTable); // <---- HERE
        centerPane.add(scrollpane); // <---- HERE
        content.add(centerPane, BorderLayout.CENTER);
        pf.setVisible(true);
      public class NewTable
        public void NewTable()
          JTable newtable = new JTable(new TableDefinition())
            protected JTableHeader createDefaultTableHeader()
              return new JTableHeader(columnModel)
                public String getToolTipText(MouseEvent mevt)
                  String tip = null;
                  java.awt.Point p = mevt.getPoint();
                  int index = columnModel.getColumnIndexAtX(p.x);
                  int realIndex = columnModel.getColumn(index).getModelIndex();
                  return colHeaderInfo[realIndex];
          initColumnSizes(newtable);
          enableCellSelection(newtable);
          newtable.setVisible(true);
        } // end of class NewTable()
      // etc
    }TIA :-)

    Hi.
    Followed you advice and used "this" instead of lical variable "newtable".
    I still don't get a display on BorderLayout.CENTER.
    The code snippet looks like this now: public class SampleView extends JApplet
      public SampleView()
        JFrame pf = new JFrame("Testing");
        Container content = pf.getContentPane();
        // ============================== CENTER
        JPanel centerPane = new JPanel(new GridLayout(2,0));
           // ============================== add new table to top half of centerPane
        NewTable DefaultNewTable = new NewTable();
        JScrollPane scrollpane = new JScrollPane(DefaultNewTable);
        centerPane.add(scrollpane);
        content.add(centerPane, BorderLayout.CENTER);
        pf.setVisible(true);
      public class NewTable extends JTable
        public void NewTable()
          JTable newtable = new JTable(new TableDefinition())
            protected JTableHeader createDefaultTableHeader()
              return new JTableHeader(columnModel)
                public String getToolTipText(MouseEvent mevt)
                  String tip = null;
                  java.awt.Point p = mevt.getPoint();
                  int index = columnModel.getColumnIndexAtX(p.x);
                  int realIndex = columnModel.getColumn(index).getModelIndex();
                  return colHeaderInfo[realIndex];
          initColumnSizes(this);
          enableCellSelection(this);
          this.setVisible(true);  // <--- This is useless!
        } // end of class NewTable()
      // etc
    }The kinda error I can't come to grip with because it compiles and run without console output... :-(

  • BUG: LR displays fast FPS series  in wrong order

    I've taken some pictureseries with my Nikon D200 with fast continious mode (5 frames per second).
    When importing them into the LR library, some of the pictures (from the fast fps series) show up in wrong order (quite annoying).
    This does not apply to pictures from "normal" shootings, just the fast fps ones.
    This happens both in folder view and other views based on keywords etc.
    I assume LR displays the pictures according to time in exif info, and doesn't know what to do when the pictures have the same time info (which I guess happens at high fps-rates).
    But wouldn't it be logical when this issue accours, that LR would look at the filenames (of the conflicting files) and display pictures chronological based on numbering. Instead, it seemes to be making wild guesses.
    My files looks like this:
    YYYYMMDD_DSC####_more_info.nef
    Is this a known issue?
    regards Carl

    David,
    I think you're right. I do a lot of continuous stuff with my D200 and I noticed some time ago it writes the files "out of order" to the card. This is really a feature of fast digital cameras and not a bug in Lightroom, it's to do with the strategy the cameras use when you give them a lot of data, pause a moment, and then do it again while they are still writing to the card. "Creation Time" is really "Write-to-Card time".
    I really can't see how it's an issue with YYYYMMDD_DSC####, though; they could still be sorted on filename post-import, surely?
    I just did a test renaming _DH35222.NEF to bananas_DH35222.NEF in the operating system; LR blinked once then updated the name, so I don't really see why the renaming couldn't in principle be done after import by a little external script, with the LR database open.
    I can't help thinking that all this renaming and reshuffling is all just making work for oneself though. The files are stored in date-based folders by default, can be sorted on (among other things) filename and (best of all) can be browsed visually.
    Still, all progress depends on the "unreasonable man" who persists in adapting the world to himself, according to George Bernard Shaw.
    Damian

  • Table of Contents displays in wrong order

    I created and generated a Table of Contents, and am having a weird issue.   It's a 19-page document, and Table of Contents is set to display Headings 1 and 2.  Everything went fine, except that on one page the Heading 1 on top of the page displays in the Table of Contents below the Heading 1 level below it - i.e., they're in the wrong order!  
    So, on the page its -
    9       Text
    10     Text
    But on the Table of Contents it returns -
    10     Text
    9       Text
    Any ideas about why it might be doing this?

    It can't be! If "9. Text" and "10. Text" use the same list for auto-numbering and "10" is below "9" on the same page, Indesign can't generate such, unless you don't copy the numbering to the TOC and instead add numbering via TOC style. Check your TOC style settings.

  • What's wrong with my code? compliation error

    There is a compilation error in my program
    but i follow others sample prog. to do, but i can't do it
    Please help me, thanks!!!
    private int selectedRow, selectedCol;
    final JTable table = new JTable(new MyTableModel());
    public temp() {     
    super(new GridLayout(1, 0));                         
    table.setPreferredScrollableViewportSize(new Dimension(600, 200));     
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);     
    ListSelectionModel rowSM = table.getSelectionModel();
    rowSM.addListSelectionListener(new ListSelectionListener() {
    public void valueChanged(ListSelectionEvent e) {
         //Ignore extra messages.
    if (e.getValueIsAdjusting()) return;
    ListSelectionModel lsm = (ListSelectionModel)e.getSource();
    if (lsm.isSelectionEmpty()) {
         System.out.println("No rows are selected.");
    else {
         selectedRow = lsm.getMinSelectionIndex();
    System.out.println("Row " + selectedRow+ " is now selected.");
    JScrollPane scrollPane = new JScrollPane(table);
    add(scrollPane);
    createPopupMenu();
    public void createPopupMenu() {       
    //Create the popup menu.
    JPopupMenu popup = new JPopupMenu();
    // display item
    JMenuItem menuItem = new JMenuItem("Delete selected");
    popup.add(menuItem);
    menuItem.addActionListener(new ActionListener(){
         public void actionPerformed(ActionEvent e){
              System.out.println("Display selected.");
              System.out.println("ClientID: "+table.getValueAt(selectedRow,0));
              int index = table.getSelectedColumn();
              table.removeRow(index);     <-------------------------------compliation error     
         }}); //what's wrong with my code? can anyone tell
    //me what careless mistake i made?
    MouseListener popupListener = new PopupListener(popup);
    table.addMouseListener(popupListener);
    public class MyTableModel extends AbstractTableModel {
    private String[] columnNames = { "ClientID", "Name", "Administrator" };
    private Vector data = new Vector();
    class Row{
         public Row(String c, String n, String a){
              clientid = c;
              name = n;
              admin = a;
         private String clientid;
         private String name;
         private String admin;
    public MyTableModel(){}
    public void removeRow(int r) {    
         data.removeElementAt(r);
         fireTableChanged(null);
    public int getColumnCount() {
    return columnNames.length;
    public int getRowCount() {
    return data.size();
    public String getColumnName(int col) {
    return columnNames[col];
    public Object getValueAt(int row, int col) {
         return "";
    public boolean isCellEditable(int row, int col) {   
    return false;
    public void setValueAt(Object value, int row, int col) {}
    }

    Inside your table model you use a Vector to hold your data. Create a method on your table model
    public void removeRow(int rowIndex)
        data.remove(rowIndex); // Remove the row from the vector
        fireTableRowDeleted(rowIndex, rowIndex); // Inform the table that the rwo has gone
    [/data]
    In the class that from which you wish to call the above you will need to add a reference to your table model.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • XML Parsing attributes with encoded ampersand causes wrong order

    Hi all,
    I am writing in the forum first (because it could be that i am doing something wrong.... but i think it is a bug. Nonetheless, i thought i'd write my problem up here first.
    I am using Java 6, and this has been reproduced on both windows and linux.
    java version "1.6.0_03"
    Problem:
    read XML file into org.w3c.dom.Document.
    XML File has some attributes which contain ampersand. These are escaped as (i think) is prescribed by the rule of XML. For example:
    <?xml version="1.0" encoding="UTF-8"?>
         <lang>
              <text dna="8233" ro="chisturi de plex coroid (&gt;=1.5 mm)" it="Cisti del plesso corioideo(&gt;=1.5mm)" tr="Koro&#305;d pleksus kisti (&gt;=1.5 mm)" pt_br="Cisto do plexo cor&oacute;ide (&gt;=1,5 mm)" de="Choroidplexus Zyste (&gt;=1,5 mm)" el="&Kappa;&#973;&sigma;&tau;&epsilon;&iota;&sigmaf; &chi;&omicron;&rho;&omicron;&epsilon;&iota;&delta;&omicron;&#973;&sigmaf; &pi;&lambda;&#941;&gamma;&mu;&alpha;&tau;&omicron;&sigmaf; (&gt;= 1.5 mm)" zh_cn="&#33033;&#32476;&#33180;&#22218;&#32959;&#65288;&gt;= 1.5 mm&#65289;" pt="Quisto do plexo coroideu (&gt;=1,5 mm)" bg="&#1050;&#1080;&#1089;&#1090;&#1072; &#1085;&#1072; &#1093;&#1086;&#1088;&#1080;&#1086;&#1080;&#1076;&#1085;&#1080;&#1103; &#1087;&#1083;&#1077;&#1082;&#1089;&#1091;&#1089; (&gt;= 1.5 mm)" fr="Kystes du plexus choroide (&gt;= 1,5 mm)" en="Choroid plexus cysts (&gt;=1.5 mm)" ru="&#1082;&#1080;&#1089;&#1090;&#1099; &#1089;&#1086;&#1089;&#1091;&#1076;&#1080;&#1089;&#1090;&#1099;&#1093; &#1089;&#1087;&#1083;&#1077;&#1090;&#1077;&#1085;&#1080;&#1081; (&gt;=1.5 mm)" es="Quiste del plexo coroideo (&gt;=1.5 mm)" ja="&#33032;&#32097;&#33180;&#22178;&#32990;&#65288;&gt;=1.5mm&#65289;" nl="Plexus choroidus cyste (&gt;= 1,5 mm)" />
    </lang>As you might understand, we need to have the fixed text '>' for later processing. (not the greater than symbol '>' but the escaped version of it).
    Therefore, I escape the ampersand (encode?) and leave the rest of the text as is. And so my > becomes >
    All ok?
    Symptom:
    in fetching attributes, for example by the getAttribute("en") type call, the wrong attribute values are fetched.
    Not only that, if i only read to Document instance, and write back to file, the attributes are shown mixed up.
    eg:
    dna: 8233, ro=chisturi de plex coroid (>=1.5 mm), en=&#1082;&#1080;&#1089;&#1090;&#1099; &#1089;&#1086;&#1089;&#1091;&#1076;&#1080;&#1089;&#1090;&#1099;&#1093; &#1089;&#1087;&#1083;&#1077;&#1090;&#1077;&#1085;&#1080;&#1081; (>=1, de=Choroidplexus Zyste (>=1,5 mm)Here you can see that 'en' is shown holding what looks like greek, ... (what is ru as a country-code anyway?) where it should have obviously had the english text that originally was associated with the attribute 'en'
    This seems very strange and unexpected to me. I would have thought that in escaping (encoding) the ampersand, i have fulfilled all requirements of me, and that should be that.
    There is also no error that seems to occur.... we simply get the wrong order when fetching attributes.
    Am I doing something wrong? Or is this a bug that should be submitted?
    Kind Regards, and thanks to all responders/readers.
    Sean
    p.s. previously I had not been escaping the ampersand. This meant that I lost my ampersand in fetching attributes, AND the attribute order was ALSO WRONG!
    In fact, the wrong order was what led me to read about how to correctly encode ampersand at all. I had been hoping that correctly encoding would fix the order problem, but it didn't.
    Edited by: svaens on Mar 31, 2008 6:21 AM

    Hi kdgregory ,
    Firstly, sorry if there has been a misunderstanding on my part. If i did not reply to the question you raised, I appologise.
    In this 'reply' I hope not to risk further misunderstanding, and have simply given the most basic example which will cause the problem I am talking about, as well as short instructions on what XML to remove to make the problem disappear.
    Secondly, as this page seems to be displayed in ISO 8859-1, this is the reason the xml I have posted looks garbled. The xml is UTF-8. I have provided a link to the example xml file for the sample below
    [example xml file UTF-8|http://sean.freeshell.org/java/less2.xml]
    As for your most recent questions:
    Is it specified as an entity? To my knowledge (so far as my understanding of what an entity is) , yes, I am including entities in my xml. In my below example, the entities are the code for the greater than symbol. I am under the understanding that this is allowed in XML ??
    Is it an actual literal character (0xA0)? No, I am specifying 'greater than' entity (code?) in order to include the actual symbol in the end result. I am encoding it in form 'ampersand', 'g character', 't character', 'colon' in order for it to work, according to information I have read on various web pages. A quick google search will show you where I got such information from, example website: https://studio.tellme.com/general/xmlprimer.html
    Here is my sample program. It is longer than the one you kindly provided only because it prints out all attributes of the element it looks for. To use it, only change the name of the file it loads.
    I have given the xml code seperately so it can be easily copied and saved to file.
    Results you can expect from running this small test example?
    1. a mixed up list of attributes where attribute node name no longer matches its assigned attribute values (not for all attributes, but some).
    2. removing the attribute bg from the 'text' element will reduce most of these symptoms, but not all. Removing another attribute from the element will most likely make the end result look normal again.
    3. No exception is thrown by the presence of non xml characters.
    IMPORTANT!!! I have only just (unfortunately) noticed what this page does to my unicode characters... all the the international characters get turned into funny codes when previewed and viewed on this page.
    Whereas the only codes I am explicitly including in this XML is the greater than symbol. The rest were international characters.
    Perhaps that is the problem?
    Perhaps there is an international characters problem?
    I am quite sure that these characters are all UTF-8 because when I open up this xml file in firefox, It displays correctly, and in checking the character encoding, firefox reports UTF-8.
    In order to provide an un-garbled xml file, I will provide it at this link:
    link to xml file: [http://sean.freeshell.org/java/less2.xml]
    Again, sorry for any hassle and/or delay with my reply, or poor reply. I did not mean to waste anyones time.
    It will be appreciated however if an answer can be found for this problem. Chiefly,
    1. Is this a bug?
    2. Is the XML correct? (if not, then all those websites i've been reading are giving false information? )
    Kindest Regards,
    Sean
    import javax.xml.parsers.DocumentBuilderFactory;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.NamedNodeMap;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import org.xml.sax.InputSource;
    public class Example
        public static void main(String[] argv)
              try
                   FileInputStream fis = new FileInputStream("/home/sean/Desktop/chris/less2.xml");
                 Document doc = DocumentBuilderFactory.newInstance()
                 .newDocumentBuilder()
                 .parse(new InputSource(fis));
                   Element root = doc.getDocumentElement();
                   NodeList textnodes = root.getElementsByTagName("text");
                   int len = textnodes.getLength();
                   int index = 0;
                   int attindex = 0;
                   int attrlen = 0;
                   NamedNodeMap attrs = null;
                   while (index<len)
                        Element te = (Element)textnodes.item(index);
                        attrs = te.getAttributes();
                        attrlen = attrs.getLength();
                        attindex = 0;
                        Node node = null;
                        while (attindex<attrlen)
                             node = attrs.item(attindex);          
                             System.out.println("attr: "+node.getNodeName()+ " is shown holding value: " + node.getNodeValue());
                             attindex++;                         
                        index++;
                        System.out.println("-------------");
                 fis.close();
              catch(Exception e)
                   System.out.println("we've had an exception, type "+ e);
    }  [example xml file|http://sean.freeshell.org/java/less2.xml]
    FOR THE XML, Please see link above, as it is UTF-8, and this page is not. Edited by: svaens on Apr 7, 2008 7:03 AM
    Edited by: svaens on Apr 7, 2008 7:23 AM
    Edited by: svaens on Apr 7, 2008 7:37 AM
    Edited by: svaens on Apr 7, 2008 7:41 AM

  • JScrollPane, what is wrong with my code?

    Hi, I appreciated if you helped me(perhaps by trying it out yourself?)
    I wanted my JScrollPane to display what is drawn on my canvas (which may be large)by scrolling, but it says it doesn't need any vertical and horizontal scroll bars. Here is the code that has this effect
    import javax.swing.*;
    import java.awt.*;
    public class WhatsWrong extends JApplet{
    public void init(){
    Container appletCont = getContentPane();
    appletCont.setLayout(new BorderLayout());
    JPanel p = new JPanel();
    p.setLayout(new BorderLayout());
    p.add(new LargeCanvas(),BorderLayout.CENTER);
    int ver = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
    int hor = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
    JScrollPane jsp = new JScrollPane(p,ver,hor);
    appletCont.add(jsp,BorderLayout.CENTER);
    class LargeCanvas extends Canvas{
    public LargeCanvas(){
    super();
    setBackground(Color.white);
    public void paint(Graphics g){
    g.drawRect(50,50,700,700);
    and the html code:
    <html>
    <body>
    <applet code="WhatsWrong" width = 300 height = 250>
    </applet>
    </body>
    </html>
    What shall I do?
    Thanks in advance.

    What is wrong with your code is that your class, LargeCanvas must implement the Scrollable interface in order to be scrolled by a JScrollPane.
    A comment regarding your use of Canvas and Swing components: The Java Tutorial recommends that you extend JPanel to do custom painting. Canvas is what they call a "heavyweight" component and they recommend not to mix lightweight (Swing) components and heavyweight components.
    There is a lot more information on custom painting on the Java Tutorial in the Lesson "Creating a GUI with Swing.

  • What's wrong with my code? please help....

    when display button is clicked it must diplay the remarks but it didn't happen...
    what's wrong with my code? please help
    here is my code.....
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.*;
    public class Area extends Applet implements ItemListener,ActionListener
         {Label arlbl = new Label("AREA");
          Choice archc = new Choice();
          Label extlbl = new Label("EXPENDITURE TYPE");
          CheckboxGroup extchk = new CheckboxGroup();
              Checkbox fchk = new Checkbox("FOOD",extchk,true);
              Checkbox schk = new Checkbox("SHELTER",extchk,false);
              Checkbox echk = new Checkbox("EDUCATION",extchk,false);
              Checkbox uchk = new Checkbox("UTILITIES",extchk,false);
          Label exalbl = new Label("EXPENDITURE AMOUNT");
          TextField exatf = new TextField("",20);
          Label remlbl = new Label("REMARKS");
          TextField remtf = new TextField("",30);
          Button disbtn = new Button("DISPLAY");
          Button resbtn = new Button("RESET");
          String display;
          public void init()
              {add(arlbl);
               archc.add("MANILA");
               archc.add("MAKATI");
               archc.add("QUEZON");
               archc.add("PASAY");
               add(archc);
               archc.addItemListener(this);
               add(extlbl);
               add(fchk);
               fchk.addItemListener(this);
               add(schk);
               schk.addItemListener(this);     
               add(echk);
               echk.addItemListener(this);
               add(uchk);
               uchk.addItemListener(this);
               add(exalbl);
               add(exatf);
               add(remlbl);
               add(remtf);
               add(disbtn);
               disbtn.addActionListener(this);
               add(resbtn);
               resbtn.addActionListener(this);
         public void itemStateChanged(ItemEvent ex)
              {int n = archc.getSelectedIndex();
               if(n==0)
                   {if(fchk.getState())
                         {exatf.setText("10000.00");
                         display = archc.getSelectedItem();
                   if(schk.getState())
                        {exatf.setText("15000.00");
                        display = archc.getSelectedItem();
                   if(echk.getState())
                        {exatf.setText("24000.00");
                        display = archc.getSelectedItem();
                   if(uchk.getState())
                        {exatf.setText("8500.00");
                        display = archc.getSelectedItem();
              if(n==1)
                   {if(fchk.getState())
                        {exatf.setText("5000.00");
                        display = archc.getSelectedItem();
                   if(schk.getState())
                        {exatf.setText("11000.00");
                        display = archc.getSelectedItem();
                   if(echk.getState())
                        {exatf.setText("7500.00");
                        display = archc.getSelectedItem();
                   if(uchk.getState())
                        {exatf.setText("24000.00");
                        display = archc.getSelectedItem();
              if(n==2)
                   {if(fchk.getState())
                        {exatf.setText("13000.00");
                        display = archc.getSelectedItem();
                   if(schk.getState())
                        {exatf.setText("7000.00");
                        display = archc.getSelectedItem();
                   if(echk.getState())
                        {exatf.setText("27000.00");
                        display = archc.getSelectedItem();
                   if(uchk.getState())
                        {exatf.setText("6000.00");
                        display = archc.getSelectedItem();
              if(n==3)
                   {if(fchk.getState())
                        {exatf.setText("6000.00");
                        display = archc.getSelectedItem();
                   if(schk.getState())
                        {exatf.setText("9000.00");
                        display = archc.getSelectedItem();
                   if(echk.getState())
                        {exatf.setText("15000.00");
                        display = archc.getSelectedItem();
                   if(uchk.getState())
                        {exatf.setText("19000.00");
                        display = archc.getSelectedItem();
         public void actionPerformed(ActionEvent e)
              {if(e.getSource() == disbtn)
                    {String amtstr = exatf.getText();
                     int amt = Integer.parseInt(amtstr);
                        {if(amt > 8000)
                             {remtf.setText(display + " IS ABOVE BUDGET");
                        else
                             {remtf.setText(display + " IS BELOW BUDGET");
              if(e.getSource() == resbtn)
                   {archc.select(0);
                   fchk.setState(true);
                   schk.setState(false);
                   echk.setState(false);
                   uchk.setState(false);
                   exatf.setText("");
                   remtf.setText("");
    Edited by: lovely23 on Feb 28, 2009 11:24 PM

    Edit: thanks for cross-posting this question on another forum. I now see that I wasted my time trying to study your code in the java-forums to help you with an answer that had already been answered elsewhere (here). Do you realize that we are volunteers, that our time is as valuable as yours? Apparently not. Cross-post again and many here will not help you again. I know that I won't.

  • What's wrong with this code (AS3)?

    I want to publish a live stream and, when a button is pressed, publish the same stream for vod.  I haven't been able to get an answer as to whether I can do this...my code is below.  Can someone please tell me if I can do this, or what may be wrong with my code?
    The live stream and playback works fine; but the recording doesn't start.  Also, I want other objects on the client, such as the current camera and audio information, and the aspect ratio being used.  I havent' been able to get these to show up (i.e., the incomingLbl and outgoingLbl do not show up).
    Thank you,
    Phillip A
    My code:
    package {
        import flash.display.MovieClip;
        import flash.net.NetConnection;
        import flash.events.NetStatusEvent; 
        import flash.events.MouseEvent;
        import flash.events.AsyncErrorEvent;
        import flash.net.NetStream;
        import flash.media.Video;
        import flash.media.Camera;
        import flash.media.Microphone;
        import fl.controls.Button;
        import fl.controls.Label;
        import fl.controls.TextArea;
        import fl.controls.CheckBox;
        public class vodcast1 extends MovieClip {
            private var nc:NetConnection;
            private var nc2:NetConnection;
            private var ns:NetStream;
            private var ns2:NetStream;
            private var nsPlayer:NetStream;
            private var vid:Video;
            private var vidPlayer:Video;
            private var cam:Camera;
            private var mic:Microphone;
            private var camr:Camera;
            private var micr:Microphone;
            private var clearBtn:Button;
            private var startRecordBtn:Button;
            private var outgoingLbl:Label;
            private var incomingLbl:Label;
            private var myMetadata:Object;
            private var outputWindow:TextArea;
            private var cb1:CheckBox;
            public function vodcast1(){
                setupUI();
                nc = new NetConnection();
                nc.addEventListener(NetStatusEvent.NET_STATUS, onNetStatus);
                nc.connect("rtmp://localhost/publishLive");
                nc2 = new NetConnection();
                nc2.connect("rtmp://localhost/vod/videos");
                nc2.addEventListener(NetStatusEvent.NET_STATUS, onNetStatus2);
            private function startRecordHandler(event:MouseEvent):void {
                publishRecordStream();
            private function onNetStatus(event:NetStatusEvent):void {
                trace(event.target + ": " + event.info.code);
                switch (event.info.code)
                    case "NetConnection.Connect.Success":
                        trace("Congratulations! you're connected to live");
                        publishCamera();
                        displayPublishingVideo();
                        displayPlaybackVideo();
                        break;
                    case "NetStream.Publish.Start":
            // NetStatus handler for Record stream       
            private function onNetStatus2(event:NetStatusEvent):void {
                trace(event.target + ": " + event.info.code);
                switch (event.info.code)
                    case "NetConnection.Connect.Success":
                        trace("Congratulations! you're connected to vod");                   
                        break;
                    case "NetConnection.Connect.Rejected":
                    case "NetConnection.Connect.Failed":
                    trace ("Oops! the connection was rejected");
                        break;
                    case "NetStream.Publish.Start":
                        sendMetadata();
                        break;
            private function asyncErrorHandler(event:AsyncErrorEvent):void {
                trace(event.text);
            private function sendMetadata():void {
                trace("sendMetaData() called")
                myMetadata = new Object();
                myMetadata.customProp = "Recording in progress";
                ns.send("@setDataFrame", "onMetaData", myMetadata);
            private function publishRecordStream():void {
                camr = Camera.getCamera();
                micr = Microphone.getMicrophone();
                ns2 = new NetStream(nc2);
                ns2.client = new Object();
                ns2.addEventListener(NetStatusEvent.NET_STATUS, onNetStatus2);
                ns2.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler);
                ns2.attachCamera(camr);
                ns2.attachAudio(micr);
                ns2.publish("vodstream", "record");           
            private function publishCamera():void {
                cam = Camera.getCamera();
                mic = Microphone.getMicrophone();
                ns = new NetStream(nc);
                ns.client = this;
                ns.addEventListener(NetStatusEvent.NET_STATUS, onNetStatus);
                ns.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler);
                ns.attachCamera(cam);
                ns.attachAudio(mic);
                ns.publish("livestream", "live");
            private function displayPublishingVideo():void {
                vid = new Video(cam.width, cam.height);
                vid.x = 10;
                vid.y = 30;
                vid.attachCamera(cam);
                addChild(vid); 
            private function displayPlaybackVideo():void {
                nsPlayer = new NetStream(nc);
                nsPlayer.client = this;
                nsPlayer.addEventListener(NetStatusEvent.NET_STATUS, onNetStatus);
                nsPlayer.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler);
                nsPlayer.play("livestream");
                vidPlayer = new Video(cam.width, cam.height);
                vidPlayer.x = cam.width + 100;
                vidPlayer.y = 30;
                vidPlayer.attachNetStream(nsPlayer);
                addChild(vidPlayer);
            private function setupUI():void {
                outputWindow = new TextArea();
                outputWindow.move(250, 175);
                outputWindow.width = 200;
                outputWindow.height = 50;
                outgoingLbl = new Label();
                incomingLbl = new Label();
                outgoingLbl.width = 100;
                incomingLbl.width = 100;
                outgoingLbl.text = "Publishing Stream";
                incomingLbl.text = "Playback Stream";
                outgoingLbl.move(20, 200);
                incomingLbl.move(300, 200);
                outgoingLbl.condenseWhite = true;
                incomingLbl.condenseWhite = true;
                startRecordBtn = new Button();
                startRecordBtn.width = 150;
                startRecordBtn.move(250, 345);
                startRecordBtn.label = "Start Recording";
                startRecordBtn.addEventListener(MouseEvent.CLICK, startRecordHandler);
                //cb1 = new CheckBox();
                //cb1.label = "Record";
                //cb1.move(135,300);
                //cb1.addEventListener(MouseEvent.CLICK,publishRecordStream);
                //clearBtn = new Button();
    //            clearBtn.width = 100;
    //            clearBtn.move(135,345);
    //            clearBtn.label = "Clear Metadata";
    //            clearBtn.addEventListener(MouseEvent.CLICK, clearHandler);
                addChild(outgoingLbl);
                addChild(incomingLbl);
    //            addChild(clearBtn);
                addChild(startRecordBtn);
    //            addChild(cb1);
                addChild(outputWindow);
            public function onMetaData(info:Object):void {
                outputWindow.appendText(info.customProp);

    use event.currentTarget (and you don't need to repeatedly define the same function):
    var c:int;
    var buttonName:String;
    for (c = 1;c < 5;c++) {
         buttonNum = "button"+c;
         this[buttonNum].addEventListener(MouseEvent.MOUSE_DOWN, pressStepButton);
    function pressStepButton(event:MouseEvent) {          trace(event.currentTarget,event.currentTarget.name);     }

  • What is wrong in this code..please

    first of all,i kindly request team please not kill me by giving suggestion using xml parser.......can u please tell how this handle in reading follwing lines....
    orderREF="1036578"><edm:OrderItem><edm:Order orderID="1036579"/> ineed to retoeve value 1036578 i use following code
    final String START6_TAG="orderREF=";
    final String END6_TAG=">";
    final String END7_TAG="/>";
    as per my observation,the follwing code need not work
    if(line.indexOf(START6_TAG)> -1 ) {
    //this code handle "orderREF=" in stands for order id
    if(line.indexOf(END7_TAG,line.indexOf(START6_TAG))>-1){ //because if we use line.indexOf(END7_TAG)it take only first indexof that..
    efound9=false;
    asper above line this code cannot excecute.but igo to loop and set flag efound9=false, what is wrong in this code for handling
    orderREF="1036578"/><edm:OrderItem><edm:Order orderID="1036579"/> this type of line that also comes in same program,here also we need output as 1036578.please tell me what i will do to hanndle these

    first of all,i kindly request team please not kill
    me by giving suggestion using xml parser.......can u
    please tell how this handle in reading follwing
    lines.... I don't understand why you are so opposed to an xml parser. You could have spent 3 hours learning how to use it and been done with this problem in the time you've spent trying to hack your way around it.
    jdom tutorials: http://www.jdom.org/downloads/docs.html
    dom4j tutorials: http://www.dom4j.org/cookbook.html

  • FileFilter????What's wrong with this code???HELP!!

    I want to limit the JFileChooser to display only txt and java file. But the code I wrote has error and I don't know what's wrong with it. can anyone help me to check it out? Thank you.
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class FileFilterTest extends JPanel
         public static void main(String[] args)
              new FileFilterTest();
         public class fFilter implements FileFilter
              public boolean accept(File file)
                   String name = file.getName();
                   if(name.toLowerCase().endsWith(".java") || name.toLowerCase().endsWith(".txt"))
                        return true;
                   else
                        return false;
         public FileFilterTest()
              JFileChooser fc = new JFileChooser();
              fc.setFileFilter(new fFilter());
              fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
              fc.setCurrentDirectory(new File(System.getProperty("user.dir")));
              //fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
              //fc.setMultiSelectionEnabled(true);
              int returnVal = fc.showDialog(FileFilterTest.this, "Open File");
              if(returnVal == JFileChooser.APPROVE_OPTION)
                   String file = fc.getSelectedFile().getPath();
                   if(file == null)
                        return;
              else if(returnVal == JFileChooser.CANCEL_OPTION)
                   System.exit(0);
              else
                   System.exit(0);
              JFrame f = new JFrame();
              FileFilterTest ff = new FileFilterTest();
              f.setTitle("FileFilterTest");
              f.setBackground(Color.lightGray);
              f.getContentPane().add(ff, BorderLayout.CENTER);
              f.setSize(800, 500);
              f.setVisible(true);
    }

    There are two file filters
    class javax.swing.filechooser.FileFilter
    interface java.io.FileFilter
    In Swing you need to make a class which extends the first one and implements the second. Sometimes you may not need to implement the second, but it is more versitle to do so and requires no extra work.

  • He material is not displayed as valuated Sale Order Stock

    Sale Order has been created and MRP execution is done at MD04.
    The Sale Order is released as Production Order.
    But when I am executing T Code  MBBS I am getting error message syaing
    The material is not displayed as valuated Sale Order Stock.
    Diagnosis
    The system has not found any stock that satisfies the selection criteria entered.
    Possible reasons for this are:
    The material does not exist. Have you entered the right material number?
    Your selection is too restrictive. The system was not able to find any stock that satisfies all selection criteria.
    The stock balance is zero.
    Procedure
    Check all the selection criteria you entered.
    Stock overview has displayed enough stock for material.
    Please adivse me how Material  can be displayed as valuated Sale Order Stock at MBBS.
    Regards

    Hi,
    Check whether the Production order execution is done and any GR has been done against the Order.
    Once the above is done, check in MBBS, the stock will sit in the Valuated SO stock.
    Even wait for any other replies.
    Thanks & Regards,
    Ravi Kumar

Maybe you are looking for

  • Message said "the file(the one i am trying to open) is not available"

    I can go into word(2010) and type a letter and then save it, but when i try to reopen the letter i get a message that say's it is not available.  Why?  What can i do to open the file, any file that i save won't open.   I have uninstalled Microsoft of

  • Duplicate subject lines and dates in Mail messages

    In a number of messages I've sent from a Samsung mobile phone to my iMac running Mail on Leopard, the messages have multiple subject lines (in some cases 7!), multiple date lines, and the from and to address is also dupliacted many times. Has anyoner

  • How do I find source files for a specific sound...

    This problem has plagued me through many version of GB. Basically, my roommate creates the garageband files, selects the instruments etc. Invariably when he gives me a copy of the Garageband file GB seems to swap in the instruments for some other ins

  • I need to know the IP will be reach thru InDesing sign in?

    My support team is asking about the IP that will be reach from InDesing sing in in Foilo builder.

  • Auto URL Encoding....WLS 5.1 vs WLS 6.1

              The below redirect use to work find in WLS 5.1. We are redirecting to login.jsp           and login.jsp will redirect to the desitination page (PageXXX.jsp) and pass the           paramter addItem to PageXXX.jsp. Therefore there are a total