3D: z-Sorting make blinking my Sprites

It seems that I can get working the z-Sorting on my projects.
I have created 3 bubbles, which are moving following an ellipsis rotation on a 2D plan laid out in 3D on the scene. During the z-Sorting, my bubbles are blinking, as if they were constantly interchanged between them.
Here is the code responsible:
private var bubbles:Vector.<Bubble> = new Vector.<Bubble>();
        public function ReorderChildren()
            bubbles.sort(function compare(x:Bubble, y:Bubble):int { return y.z - x.z; });
            for (var ind:int = 0; ind < bubbles.length; ind++)
                root.addChild(bubbles[ind]);
However, it seems that removing the for loop (which performs root.addChild), and apply the same sorting function upon the vector, bubbles are still blinking.
var bubbles:Vector.<Bubble> = new Vector.<Bubble>();
// Adding bubbles to the scene
for each (var flyer:FlyerVO in flyers) {
    var bubble:Bubble = new Bubble(flyer);
    root.addChildAt(bubble);
    bubbles.push(bubble);
public function ReorderChildren() {
    bubbles.sort(function compare(x:Bubble, y:Bubble):int { return y.z - x.z; });
The simple fact that sorting the vector (which contains only references to Bubble object) make them blink. Is this a bug ?
> Is there any way to attach my project folder to illustrate the bug ?

wow... I guess getting to the question instead of going over, no doubt important, details.
If you would test the snippets in a real environment you'd see the result. Just a reassuring confirmation to the original poster maybe...
Past following code in frame one of .fla and see the effect on the indicated lines (after some code alterations I noticed it disappearing with some sorts and it not appearing at all with just two 'conficting' positions:
import flash.display.Sprite;
import flash.events.Event;
var bubbles:Vector.<Sprite> = new Vector.<Sprite>();
var s:Sprite;
s = createCircle( 0xFF0000 );
s.x = 200;
s.y = 200;
s.z = 10;
bubbles.push( s );
s = createCircle( 0x00FF00 );
s.x = 220;
s.y = 220;
s.z = 20;
bubbles.push( s );
s = createCircle( 0x0000FF );
s.x = 200;
s.y = 240;
s.z = 20;
bubbles.push( s );
// remove next circle creation to not see effect
s = createCircle( 0xFF00FF );
s.x = 180;
s.y = 220;
s.z = 20;
bubbles.push( s );
addEventListener( Event.ENTER_FRAME, ReorderChildren );
function createCircle( c:int ):Sprite
     var s:Sprite = new Sprite();
     s.graphics.beginFill( c );
     s.graphics.drawCircle( 0, 0, 20 );
     s.graphics.endFill();
     return s;
function ReorderChildren( event:Event )
     //bubbles.sort( highFirst ); // OK
     //bubbles.sort( lowFirst ); // jitter
     bubbles.sort( compare ); // jitter
     for (var ind:int = 0; ind < bubbles.length; ind++)
          addChild(bubbles[ind]);
function compare(a:Sprite, b:Sprite):int
     return b.z - a.z;
// higest value first in array
function highFirst(a:Sprite, b:Sprite):int
     if( a.z > b.z )
             return 1;
     else if ( a.z < b.z )
             return -1;
     else
          return 0;
// higest value first in array
function lowFirst(a:Sprite, b:Sprite):int
     if( a.z < b.z )
             return 1;
     else if ( a.z > b.z )
             return -1;
     else
          return 0;
However, testing some nicer, AFAIK also technically correct, code I get no nasty sorting problems:
import flash.display.Sprite;
import flash.events.Event;
import flash.geom.Point;
var bubbles:Vector.<Sprite> = new Vector.<Sprite>();
var s:Sprite;
var p:Point;
var center:Point = new Point( 200, 200 );
s = createCircle( 0xFF0000 );
p = Point.polar( 20, 0 * Math.PI / 180 ).add( center );
s.x = p.x;
s.y = p.y;
s.z = 20;
bubbles.push( s );
s = createCircle( 0x00FF00 );
p = Point.polar( 20, 120 * Math.PI / 180 ).add( center );
s.x = p.x;
s.y = p.y;
s.z = 20;
bubbles.push( s );
s = createCircle( 0x0000FF );
p = Point.polar( 20, 240 * Math.PI / 180 ).add( center );
s.x = p.x;
s.y = p.y;
s.z = 20;
bubbles.push( s );
addEventListener( Event.ENTER_FRAME, ReorderChildren );
function createCircle( c:int ):Sprite
     var s:Sprite = new Sprite();
     s.graphics.beginFill( c );
     s.graphics.drawCircle( 0, 0, 20 );
     s.graphics.endFill();
     return s;
function ReorderChildren( event:Event )
     //bubbles.sort( highFirst );
     bubbles.sort( lowFirst );
     //bubbles.sort(function compare(x:Sprite, y:Sprite):int { return y.z - x.z; });
     for (var ind:int = 0; ind < bubbles.length; ind++)
          addChild(bubbles[ind]);
          trace( bubbles[ind].z );
// higest value first in array
function highFirst(a:Sprite, b:Sprite):int
     if( a.z > b.z )
             return 1;
     else if ( a.z < b.z )
             return -1;
     else
          return 0;
// higest value first in array
function lowFirst(a:Sprite, b:Sprite):int
     if( a.z < b.z )
             return 1;
     else if ( a.z > b.z )
             return -1;
     else
          return 0;
If you wish to have a go.
Kind regards,
Manno

Similar Messages

  • APEX report sorting makes report slow

    Hi,
    I have some reports in APEX that are fast (3 sec) when I have no sorting enabled and they turn slow (20 sec) when I enable column sorting.
    The reports are based on data running over a DB-link, all tables come from the same DB-link. When I launch the queries (with filled in parameters) in SQL+ then it takes no more then 5 sec (with or without sorting). The result is about 1000 to 2000 records (only showing 25 in the report with pagination).
    How can I make the report fast (less then 5 sec) with sorting enabled?
    Is there any known bug in APEX that is the source of my problem?
    Thanks in advance.

    Good point, but I already have recreated the report (delete and recreate) with no result. Cause I know that sometimes the reports run slow, cause they are somehow confused with the sorting, and in most cases it helps to recreate the report (which resets the report ID, so that it's like clearing the user preferences).
    First I thougt it had to do something with the user preferences, but I think that it is something different.
    I really don't know how to explain the time difference between SQL+ and APEX.

  • How can I make blinking eyes stay open?

    I have a shot where a stationary guy is getting sprayed in the face with a fire extinguisher. The actor knows it's coming so he blinks in the split second before he's sprayed. Can I make the pixels from the open eyes, stay where they are in the frames that follow, so that the closed eye pixels are covered with the open eye pixels?

    Roto the eyes so only the eyes are visible, set an in and out point just before the blink so the eyes stay open, move the layer in time to cover the blink.
    If the camera moves or the head moves you have to adjust the position and maybe animate it. That's all there is to it. Layers and time shift.

  • Sorting makes the report slow

    Hi,
    I need to sort the SQL (APEX_ITEM) report. I created a hidden item and used the hidden item to sort the report. Its working fine but making the report very slow.
    If I remove the sorting, then the report runs fast.
    Please let me know what should do to make it faster.
    Thanks.

    Hi Denes,
    Here is my query:
    SELECT apex_item.hidden (21, R.pk) || apex_item.hidden (22, R.imo) || apex_item.hidden (23, wwv_flow_item.md5 ( R.PK ,R.RQMT )) ||
    apex_item.hidden (24,R.imso)|| apex_item.hidden (25, R.installation_number )|| apex_item.hidden (26, R.base_code) ||
    apex_item.text (27, R.year, 80,100,
    'style="width:40px;text-align:right;'
    || 'color:solid darkgreen;background-color:#FFF4BF;font-weight:bold" readonly="readonly" title="Year"', 'f27_' || LPAD (ROWNUM, 4, '0')) year ,
    apex_item.text (28, R.fcg, 80, 100,
    'style="width:64px;text-align:right;'
    || 'color:solid darkgreen;background-color:#FFF4BF;font-weight:bold" readonly="readonly" title="Fcg"', 'f28_' || LPAD (ROWNUM, 4, '0')) fcg,
    apex_item.text (29, R.IMO_NAME, 80, 100,
    'style="width:90px;text-align:right;'
    || 'color:solid darkgreen;background-color:#FFF4BF;font-weight:bold" readonly="readonly"title="Imo"', 'f29_' || LPAD (ROWNUM, 4, '0')) IMO_NAME,
    apex_item.text (30, R.IMSO_NAME, 80, 100,
    'style="width:96px;text-align:right;'
    || 'color:solid darkgreen;background-color:#FFF4BF;font-weight:bold" readonly="readonly" title="Imso"', 'f30_' || LPAD (ROWNUM, 4, '0')) IMSO_NAME,
    apex_item.text (31, R.installation_NAME, 80, 100,
    'style="width:140px;text-align:right;'
    || 'color:solid darkgreen;background-color:#FFF4BF;font-weight:bold" readonly="readonly" title="Installation"', 'f31_' || LPAD (ROWNUM, 4, '0')) INSTALLATION_NAME,
    apex_item.text (32, R.BASE_NAME, 80, 100,
    'style="width:160px;text-align:right;'
    || 'color:solid darkgreen;background-color:#FFF4BF;font-weight:bold" readonly="readonly"title="Base"','f32_' || LPAD (ROWNUM, 4, '0'))BASE_NAME,
    apex_item.hidden (33, R.FCG_DESC) ||
    apex_item.text (34,R.FAC, 80, 100,
    'style="width:75px;text-align:right;'
    || 'color:solid darkgreen;background-color:#FFF4BF;font-weight:bold" readonly="readonly"title="Fac"','f34_' || LPAD (ROWNUM, 4, '0')) FAC,
    apex_item.hidden (35, R.FAC_DESC)||
    apex_item.text (36, R.EFR, 80, 100,
    'style="width:75px;text-align:right;'
    || 'color:solid darkgreen;background-color:#FFF4BF;font-weight:bold" readonly="readonly"title="Efr"', 'f36_' || LPAD (ROWNUM, 4, '0')) EFR,
    apex_item.hidden (37,R.EFR_DESC) ||
    case when
    get_PK_status(R.PK) IN ('Edited','Reviewed','Approved') and
    :P2_Role = 'EDITOR' then
    apex_item.text (38, R.rqmt,80,100,
    'style="width:75px;text-align:right;'
    || 'color:solid darkgreen;background-color:#FFF4BF;font-weight:bold" readonly="readonly"title="Requirement"', 'f38_' || LPAD (ROWNUM, 4, '0'))
    when
    nvl(get_PK_status(R.PK),'X') not in ('Edited','Reviewed','Approved') and
    :P2_Role = 'EDITOR' then
    apex_item.text (38,R.RQMT,
    80, 100,
    'style="border:1.3px solid black;width:75px;text-align:right;'
    || 'color:darkblue;font-weight:bold title="Requirement"',
    'f38_' || LPAD (ROWNUM, 4,'0'))
    when
    get_PK_status(R.PK) IN ('Edited','Reviewed','Approved','Disapproved') and
    :P2_Role = 'REVIEWER' then
    apex_item.text (38,R.rqmt,80,100,
    'style="width:75px;text-align:right;'
    || 'color:solid darkgreen;background-color:#FFF4BF;font-weight:bold" readonly="readonly"title="Requirement"', 'f38_' || LPAD (ROWNUM, 4, '0'))
    when
    nvl(get_PK_status(R.PK),'X') NOT IN ('Edited') and
    :P2_Role = 'REVIEWER' then
    apex_item.text (38, R.rqmt,80,100,
    'style="width:75px;text-align:right;'
    || 'color:solid darkgreen;background-color:#FFF4BF;font-weight:bold" readonly="readonly"title="Requirement"', 'f38_' || LPAD (ROWNUM, 4, '0'))
    when get_PK_status(R.PK) = 'Edited' and
    :P2_Role = 'REVIEWER' then
    apex_item.text (38, R.RQMT,80,100,
    'style="width:75px;text-align:right;'
    || 'color:darkblue;font-weight:bold title="Requirement"',
    'f38_' || LPAD (ROWNUM, 4, '0'))
    when get_PK_status(R.PK) IN ('Edited','Reviewed','Approved','Disapproved') and
    :P2_Role = 'APPROVER' then
    apex_item.text (38, R.rqmt,80,100,
    'style="width:75px;text-align:right;'
    || 'color:solid darkgreen;background-color:#FFF4BF;font-weight:bold" readonly="readonly"title="Requirement"', 'f38_' || LPAD (ROWNUM, 4, '0'))
    when nvl(get_PK_status(R.PK),'X') NOT IN ('Reviewed') and
    :P2_Role = 'APPROVER' then
    apex_item.text (38, R.rqmt,80,100,
    'style="width:75px;text-align:right;'
    || 'color:solid darkgreen;background-color:#FFF4BF;font-weight:bold" readonly="readonly"title="Requirement"', 'f38_' || LPAD (ROWNUM, 4, '0'))
    when get_PK_status(R.PK) = 'Reviewed' and
    :P2_Role = 'APPROVER' then
    apex_item.text (38,R.RQMT,80, 100,
    'style="width:75px;text-align:right;'
    || 'color:darkblue;font-weight:bold title="Requirement"',
    'f38_' || LPAD (ROWNUM, 4, '0'))
    end RQMT,
    case when get_PK_status(R.PK) = 'Edited' and
    :P2_Role in('EDITOR','REVIEWER','APPROVER') then
    apex_item.text (39, RU.RQMT, 80, 100,
    'style="width:75px;text-align:right;'
    || 'color:solid darkred;background-color:yellow;font-weight:bold " readonly="readonly"title="Edited"' , 'f39_' || LPAD (ROWNUM, 4, '0'))
    when nvl(get_PK_status(R.PK),'X') NOT IN ('Edited','Reviewed','Approved','NotReviewed','Disapproved') and
    :P2_Role in('EDITOR','REVIEWER','APPROVER') then
    apex_item.text (39, RU.RQMT, 80, 100,
    'style="width:75px;text-align:right;'
    || 'color:solid darkred;background-color:#FFF4BF;font-weight:bold " readonly="readonly"title="New Requirement"' , 'f39_' || LPAD (ROWNUM, 4, '0'))
    when get_PK_status(R.PK) IN ('Reviewed') and
    :P2_Role in('EDITOR','REVIEWER','APPROVER') then
    apex_item.text (39, RU.RQMT, 80, 100,
    'style="width:75px;text-align:right;'
    || 'color:solid darkred;background-color:lime;font-weight:bold " readonly="readonly"title="Reviewed"' , 'f39_' || LPAD (ROWNUM, 4, '0'))
    when get_PK_status(R.PK) IN ('Approved') and
    :P2_Role in('EDITOR','REVIEWER','APPROVER') then
    apex_item.text (39, RU.RQMT, 80, 100,
    'style="width:75px;text-align:right;'
    || 'color:solid black;background-color:#DAFFBF;font-weight:bold " readonly="readonly"title="Approved"' , 'f39_' || LPAD (ROWNUM, 4, '0'))
    when get_PK_status(R.PK) IN ('Disapproved') and
    :P2_Role in('EDITOR','REVIEWER','APPROVER') then
    apex_item.text (39, RU.RQMT, 80, 100,
    'style="width:75px;text-align:right;'
    || 'color:SOLID black;background-color:RED;font-weight:bold " readonly="readonly"title="Not Approved"' , 'f39_' || LPAD (ROWNUM, 4, '0'))
    when get_PK_status(R.PK) IN ('NotReviewed') and
    :P2_Role in('EDITOR','REVIEWER','APPROVER') then
    apex_item.text (39, RU.RQMT, 80, 100,
    'style="width:75px;text-align:right;'
    || 'color:SOLID black;background-color:orange;font-weight:bold " readonly="readonly"title="Not Reviewed"' , 'f39_' || LPAD (ROWNUM, 4, '0'))
    end NEW_RQMT,
    apex_item.text (40, RU.Status, 80,100,
    'style="width:75px;text-align:right;'
    || 'color:solid darkgreen;background-color:#FFF4BF;font-weight:bold " readonly="readonly"title="Status"', 'f40_' || LPAD (ROWNUM, 4, '0')) STATUS ,
    CASE WHEN (get_PK_status(R.PK) IN('Edited','Reviewed','NotReviewed') and :P2_Role = 'APPROVER') THEN APEX_ITEM.SELECT_LIST(41,'Approved','Approved;Approved,Disapproved;Disapproved','','title="This field is only for Reviewers and Approvers"')
    WHEN (get_PK_status(R.PK) = 'Edited' and :P2_Role = 'REVIEWER') THEN
    APEX_ITEM.SELECT_LIST(41,'Reviewed','Reviewed;Reviewed,NotReviewed;NotReviewed','','title="This field is only for Reviewers and Approvers"')
    ELSE
    APEX_ITEM.SELECT_LIST(41,'','','title="This field is only for Reviewers and Approvers"')
    END ACTION ,
    '<a href="javascript:popUp2('''
    || 'f?p=&APP_ID.:3:&SESSION.::NO::P2_PK:'
    || R.PK
    || ''', 1200, 500);">'
    || '<img src="#APP_IMAGES#blue_book_open.gif" title="View Row History" >'
    || '</a>' History
    from rplans_sumtab R,
    (SELECT PK, RQMT, STATUS, DATE_CREATED FROM RPLANS_USER_SUMTAB R1
    WHERE DATE_CREATED = (SELECT MAX(DATE_CREATED) FROM RPLANS_USER_SUMTAB R2
    WHERE R2.PK = R1.PK)) RU
    WHERE R.PK = RU.PK(+)
    2.) The pagination I am using is:
    Row Ranges 1-15 16-30 (with set pagination)
    3)The table has only 1000 records.
    The report runs very fast when I don't use sorting, but when I use sorting, it becomes very slow.
    Thanks.

  • Help please: Duplicate an image and make a scripted sprite

    Trying to duplicate an image from an existing cast member
    (named “capsule”) and then place that image as a sprite
    on the stage. I can duplicate the image, but I don’t know how
    to place it on the stage. Using makeScriptedSprite requires a cast
    member, not an image reference. Do I need to make my duplicated
    image into a cast member? The documentation seems to advise against
    doing this at runtime due to memory management.
    How would you folks go about duplicating an image from the
    cast and placing on the stage dynamically during runtime?

    Thanks for your responses wherold and openspark.
    I don't need to duplicate the cast member, just the image of
    the cast member.
    Here is the grand scheme. Imagine cast member 1 is a bitmap
    of a wall. Each round of the game, I need to place the wall on
    stage. Additionally, I need to use a different cast member
    (hole.bmp) to punch 3 to 5 holes through the wall image on the
    stage.
    Each round will be different, so I thought that I needed to
    duplicate the wall every time, otherwise the cast member itself
    would have more and more holes cut out over time. I need a fresh
    wall each round.
    Any thoughts?

  • Treeview control - How to make a node blink?

    Hi,
    Is there a "elegant" way to make blink a treeview node?
    I am thinking to use a timer with the collection of nodes that I want to make the blink effect, and update the icon ...

    Hi,
    You can develop your custom control for this purpose. The logic you mentioned was correct. Here is a sample control that I developed by the logic you mentioned.
    public class BlinkingTreeView : TreeView
    private Timer t = new Timer();
    private List<TreeNode> blinkingNodes = new List<TreeNode>();
    public BlinkingTreeView()
    t.Interval = 1000;
    t.Tick += new EventHandler(t_Tick);
    bool isNodeBlinked = false;
    void t_Tick(object sender, EventArgs e)
    foreach (TreeNode tn in blinkingNodes)
    if (isNodeBlinked)
    //update Icon
    tn.Text = tn.Text.Substring(0, tn.Text.Length - 1);//to test
    isNodeBlinked = false;
    else
    //update Icon
    tn.Text = tn.Text + "*";//to test
    isNodeBlinked = true;
    public void AddBlinkNode(TreeNode n)
    blinkingNodes.Add(n);
    public void RemoveBlinkNode(TreeNode n)
    blinkingNodes.Remove(n);
    public void ClearBlinkNodes()
    blinkingNodes.Clear();
    public List<TreeNode> BlinkingNodes
    get { return blinkingNodes; }
    public int BlinkInterval
    get { return t.Interval; }
    set { t.Interval = value; }
    public void StartBlinking()
    isNodeBlinked = false;
    t.Enabled = true;
    public void StopBlinking()
    t.Enabled = false;

  • Text slide horizontal and blinking

    Hello:
    Can you give some samples of two effects for text:
    1.- move text horizontally
    2.- make blink the text (moving or not).
    Many thanks to all.

    Attach this behavior to the text sprite:
    property thisSprite, howFar
    on beginSprite me
    thisSprite = me.spriteNum
    end
    on getPropertyDescriptionList
    myPropList = [:]
    myPropList.addProp(#howFar,[#comment:"select the number of
    pixels to
    move:",#format:#integer,#range:[#min:-10,#max:10],#default:3])
    return myPropList
    end
    on exitFrame me
    sprite(thisSprite).locH = sprite(thisSprite).locH + howFar
    sprite(thisSprite).visible = not sprite(thisSprite).visible
    end

  • My Apple TV is not working apple emblem is blinking but when I try remote nothing happens. I have unplugged both Apple TV and wifi. Thank you

    Apole tv shows apple emblem blinking every 3-4 seconds. Remote only makes blinking light on remote stop flashing.

    Try to restore your Apple TV via iTunes application on your computer:
    Apple TV (2nd and 3rd generation): Restoring your Apple TV - Apple Support

  • JTable sorting - problem when adding elements (complete code inside)

    I�m writing this email with reference to a recent posting here but this time with the code example. (I apologize for the duplicated posting � this time it will be with the code)
    Problem: when adding more elements to the JTable (sorted) the exception: ArrayIndexOutOfBoundsException is thrown.
    Example: If the elements in the table are 10 and then the user requests for 8 � the table will produce the correct result. However, if the user will ask for 11 items (>10) the exception will be thrown.
    The program: The program below (compiles and running). A JTable is constructed with 3 items, when you click the button - the return result should be 4 items - this will generate the error, WHY?
    I would highly appreciate your thoughts why this is happening and most importantly � how to fix it.
    Thanks a lot
    3 files:
    (1) TableSorterDemo
    (2) Traveler
    (3)TableSorter
    //TableSorterDemo:
    package sorter;
    import javax.swing.DefaultListModel;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    * TableSorterDemo is like TableDemo, except that it
    * inserts a custom model -- a sorter -- between the table
    * and its data model.  It also has column tool tips.
    public class TableSorterDemo implements ActionListener
         private JPanel superPanel;
         private JButton clickMe = new JButton("click me to get diff data");
         private boolean DEBUG = false;
         private DefaultListModel defaultListModel;
         private JTable table;
        public TableSorterDemo()
             superPanel = new JPanel(new BorderLayout());
             defaultListModel = new DefaultListModel();
             init1();
            TableSorter sorter = new TableSorter(new MyTableModel(defaultListModel)); //ADDED THIS     
            table = new JTable(sorter);             //NEW
            sorter.setTableHeader(table.getTableHeader()); //ADDED THIS
            table.setPreferredScrollableViewportSize(new Dimension(500, 70));
            //Set up tool tips for column headers.
            table.getTableHeader().setToolTipText(
                    "Click to specify sorting; Control-Click to specify secondary sorting");
            //Create the scroll pane and add the table to it.
            JScrollPane scrollPane = new JScrollPane(table);
            //Add the scroll pane to this panel.
            superPanel.add("Center", scrollPane);
            superPanel.add("South",clickMe);
            clickMe.addActionListener(this);              
        public JPanel getPanel()
             return superPanel;
        public void init1()
             //in real life this will be done from the db
             Traveler a = new Traveler();
             Traveler b = new Traveler();
             Traveler c = new Traveler();
             a.setFirstName("Elvis");
             a.setLastName("Presley");
             a.setSprot("Ping Pong");
             a.setNumYears(3);
             a.setVegetarian(true);
             b.setFirstName("Elton");
             b.setLastName("John");
             b.setSprot("Soccer");
             b.setNumYears(2);
             b.setVegetarian(true);
             c.setFirstName("shaquille");
             c.setLastName("oneil");
             c.setSprot("Golf");
             c.setNumYears(22);
             c.setVegetarian(true);
             defaultListModel.addElement(a);
             defaultListModel.addElement(b);
             defaultListModel.addElement(c);
        public void init2()
             //in real life this will be done from the db
             Traveler d = new Traveler();
             Traveler e = new Traveler();
             Traveler f = new Traveler();
             Traveler g = new Traveler();
             d.setFirstName("John");
             d.setLastName("Smith");
             d.setSprot("Tennis");
             d.setNumYears(32);
             d.setVegetarian(true);
             e.setFirstName("Ron");
             e.setLastName("Cohen");
             e.setSprot("Baseball");
             e.setNumYears(12);
             e.setVegetarian(true);
             f.setFirstName("Donald");
             f.setLastName("Mac Novice");
             f.setSprot("Vallyball");
             f.setNumYears(1);
             f.setVegetarian(true);
             g.setFirstName("Eithan");
             g.setLastName("Superstar");
             g.setSprot("Vallyball");
             g.setNumYears(21);
             g.setVegetarian(true);
             defaultListModel.addElement(d);
             defaultListModel.addElement(e);
             defaultListModel.addElement(f);
             defaultListModel.addElement(g);            
        class MyTableModel extends AbstractTableModel
             private DefaultListModel myModel;
             public MyTableModel(DefaultListModel m)
                  myModel=m;
            private String[] columnNames = {"First Name",
                                            "Last Name",
                                            "Sport",
                                            "# of Years",
                                            "Vegetarian"};
            public int getColumnCount()
                return columnNames.length;
            public int getRowCount()
                return myModel.size();
            public String getColumnName(int column)
                 return getNames()[column];             
             public String[] getNames()
                  String[] names = {"First Name", "Last Name", "Sport", "# of Years", "Vegetarian"};
                  return names;
            public Object getValueAt(int row, int col)
                 return distributeObjectsInTable(row, col, (Traveler) myModel.elementAt(row));
            public Object distributeObjectsInTable(int row, int col, Traveler tr)
               switch(col)
                         case 0:
                              return tr.getFirstName();
                         case 1:
                           return tr.getLastName();
                      case 2:
                           return tr.getSprot();
                      case 3:
                           return new Integer(tr.getNumYears());
                      case 4:
                           return new Boolean (tr.isVegetarian());
                     default:
                         return "Error";
            public Class getColumnClass(int c)
                return getValueAt(0, c).getClass();
        private static void createAndShowGUI()
            //Make sure we have nice window decorations.
            JFrame.setDefaultLookAndFeelDecorated(true);
            //Create and set up the window.
            JFrame frame = new JFrame("TableSorterDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            TableSorterDemo newContentPane = new TableSorterDemo();
            newContentPane.getPanel().setOpaque(true); //content panes must be opaque
            frame.setContentPane(newContentPane.getPanel());
            //Display the window.
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args)
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable()                   
                public void run()
                    createAndShowGUI();
         public void actionPerformed(ActionEvent ae)
              if (ae.getSource()==clickMe)
                   defaultListModel.removeAllElements();
                   init2(); //if the size of the model was less than 2 items - the result will be ok.
                              //in other words, if you commens the last 2 rows of this method (addElement(f) & g)
                             // the result will be fine.
                   table.updateUI();          
    }//(2) Traveler
    package sorter;
    public class Traveler
         private String firstName;
         private String lastName;
         private String sprot;
         private int numYears;
         private boolean vegetarian;
         public String getFirstName()
              return firstName;
         public String getLastName()
              return lastName;
         public int getNumYears()
              return numYears;
         public String getSprot()
              return sprot;
         public boolean isVegetarian()
              return vegetarian;
         public void setFirstName(String firstName)
              this.firstName = firstName;
         public void setLastName(String lastName)
              this.lastName = lastName;
         public void setNumYears(int numYears)
              this.numYears = numYears;
         public void setSprot(String sprot)
              this.sprot = sprot;
         public void setVegetarian(boolean vegetarian)
              this.vegetarian = vegetarian;
    }//(3)TableSorter
    package sorter;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.util.List;
    import javax.swing.*;
    import javax.swing.event.TableModelEvent;
    import javax.swing.event.TableModelListener;
    import javax.swing.table.*;
    public class TableSorter extends AbstractTableModel {
        protected TableModel tableModel;
        public static final int DESCENDING = -1;
        public static final int NOT_SORTED = 0;
        public static final int ASCENDING = 1;
        private static Directive EMPTY_DIRECTIVE = new Directive(-1, NOT_SORTED);
        public static final Comparator COMPARABLE_COMAPRATOR = new Comparator() {
            public int compare(Object o1, Object o2) {
                return ((Comparable) o1).compareTo(o2);
        public static final Comparator LEXICAL_COMPARATOR = new Comparator() {
            public int compare(Object o1, Object o2) {
                return o1.toString().compareTo(o2.toString());
        private Row[] viewToModel;
        private int[] modelToView;
        private JTableHeader tableHeader;
        private MouseListener mouseListener;
        private TableModelListener tableModelListener;
        private Map columnComparators = new HashMap();
        private List sortingColumns = new ArrayList();
        public TableSorter() {
            this.mouseListener = new MouseHandler();
            this.tableModelListener = new TableModelHandler();
        public TableSorter(TableModel tableModel) {
            this();
            setTableModel(tableModel);
        public TableSorter(TableModel tableModel, JTableHeader tableHeader) {
            this();
            setTableHeader(tableHeader);
            setTableModel(tableModel);
        private void clearSortingState() {
            viewToModel = null;
            modelToView = null;
        public TableModel getTableModel() {
            return tableModel;
        public void setTableModel(TableModel tableModel) {
            if (this.tableModel != null) {
                this.tableModel.removeTableModelListener(tableModelListener);
            this.tableModel = tableModel;
            if (this.tableModel != null) {
                this.tableModel.addTableModelListener(tableModelListener);
            clearSortingState();
            fireTableStructureChanged();
        public JTableHeader getTableHeader() {
            return tableHeader;
        public void setTableHeader(JTableHeader tableHeader) {
            if (this.tableHeader != null) {
                this.tableHeader.removeMouseListener(mouseListener);
                TableCellRenderer defaultRenderer = this.tableHeader.getDefaultRenderer();
                if (defaultRenderer instanceof SortableHeaderRenderer) {
                    this.tableHeader.setDefaultRenderer(((SortableHeaderRenderer) defaultRenderer).tableCellRenderer);
            this.tableHeader = tableHeader;
            if (this.tableHeader != null) {
                this.tableHeader.addMouseListener(mouseListener);
                this.tableHeader.setDefaultRenderer(
                        new SortableHeaderRenderer(this.tableHeader.getDefaultRenderer()));
        public boolean isSorting() {
            return sortingColumns.size() != 0;
        private Directive getDirective(int column) {
            for (int i = 0; i < sortingColumns.size(); i++) {
                Directive directive = (Directive)sortingColumns.get(i);
                if (directive.column == column) {
                    return directive;
            return EMPTY_DIRECTIVE;
        public int getSortingStatus(int column) {
            return getDirective(column).direction;
        private void sortingStatusChanged() {
            clearSortingState();
            fireTableDataChanged();
            if (tableHeader != null) {
                tableHeader.repaint();
        public void setSortingStatus(int column, int status) {
            Directive directive = getDirective(column);
            if (directive != EMPTY_DIRECTIVE) {
                sortingColumns.remove(directive);
            if (status != NOT_SORTED) {
                sortingColumns.add(new Directive(column, status));
            sortingStatusChanged();
        protected Icon getHeaderRendererIcon(int column, int size) {
            Directive directive = getDirective(column);
            if (directive == EMPTY_DIRECTIVE) {
                return null;
            return new Arrow(directive.direction == DESCENDING, size, sortingColumns.indexOf(directive));
        private void cancelSorting() {
            sortingColumns.clear();
            sortingStatusChanged();
        public void setColumnComparator(Class type, Comparator comparator) {
            if (comparator == null) {
                columnComparators.remove(type);
            } else {
                columnComparators.put(type, comparator);
        protected Comparator getComparator(int column) {
            Class columnType = tableModel.getColumnClass(column);
            Comparator comparator = (Comparator) columnComparators.get(columnType);
            if (comparator != null) {
                return comparator;
            if (Comparable.class.isAssignableFrom(columnType)) {
                return COMPARABLE_COMAPRATOR;
            return LEXICAL_COMPARATOR;
        private Row[] getViewToModel() {
            if (viewToModel == null) {
                int tableModelRowCount = tableModel.getRowCount();
                viewToModel = new Row[tableModelRowCount];
                for (int row = 0; row < tableModelRowCount; row++) {
                    viewToModel[row] = new Row(row);
                if (isSorting()) {
                    Arrays.sort(viewToModel);
            return viewToModel;
        public int modelIndex(int viewIndex)
            return getViewToModel()[viewIndex].modelIndex;
        private int[] getModelToView()
            if (modelToView == null) {
                int n = getViewToModel().length;
                modelToView = new int[n];
                for (int i = 0; i < n; i++) {
                    modelToView[modelIndex(i)] = i;
            return modelToView;
        // TableModel interface methods
        public int getRowCount() {
            return (tableModel == null) ? 0 : tableModel.getRowCount();
        public int getColumnCount() {
            return (tableModel == null) ? 0 : tableModel.getColumnCount();
        public String getColumnName(int column) {
            return tableModel.getColumnName(column);
        public Class getColumnClass(int column) {
            return tableModel.getColumnClass(column);
        public boolean isCellEditable(int row, int column) {
            return tableModel.isCellEditable(modelIndex(row), column);
        public Object getValueAt(int row, int column) {
            return tableModel.getValueAt(modelIndex(row), column);
        public void setValueAt(Object aValue, int row, int column) {
            tableModel.setValueAt(aValue, modelIndex(row), column);
        // Helper classes
        private class Row implements Comparable {
            private int modelIndex;
            public Row(int index) {
                this.modelIndex = index;
            public int compareTo(Object o) {
                int row1 = modelIndex;
                int row2 = ((Row) o).modelIndex;
                for (Iterator it = sortingColumns.iterator(); it.hasNext();) {
                    Directive directive = (Directive) it.next();
                    int column = directive.column;
                    Object o1 = tableModel.getValueAt(row1, column);
                    Object o2 = tableModel.getValueAt(row2, column);
                    int comparison = 0;
                    // Define null less than everything, except null.
                    if (o1 == null && o2 == null) {
                        comparison = 0;
                    } else if (o1 == null) {
                        comparison = -1;
                    } else if (o2 == null) {
                        comparison = 1;
                    } else {
                        comparison = getComparator(column).compare(o1, o2);
                    if (comparison != 0) {
                        return directive.direction == DESCENDING ? -comparison : comparison;
                return 0;
        private class TableModelHandler implements TableModelListener {
            public void tableChanged(TableModelEvent e) {
                // If we're not sorting by anything, just pass the event along.            
                if (!isSorting()) {
                    clearSortingState();
                    fireTableChanged(e);
                    return;
                // If the table structure has changed, cancel the sorting; the            
                // sorting columns may have been either moved or deleted from            
                // the model.
                if (e.getFirstRow() == TableModelEvent.HEADER_ROW) {
                    cancelSorting();
                    fireTableChanged(e);
                    return;
                // We can map a cell event through to the view without widening            
                // when the following conditions apply:
                // a) all the changes are on one row (e.getFirstRow() == e.getLastRow()) and,
                // b) all the changes are in one column (column != TableModelEvent.ALL_COLUMNS) and,
                // c) we are not sorting on that column (getSortingStatus(column) == NOT_SORTED) and,
                // d) a reverse lookup will not trigger a sort (modelToView != null)
                // Note: INSERT and DELETE events fail this test as they have column == ALL_COLUMNS.
                // The last check, for (modelToView != null) is to see if modelToView
                // is already allocated. If we don't do this check; sorting can become
                // a performance bottleneck for applications where cells 
                // change rapidly in different parts of the table. If cells
                // change alternately in the sorting column and then outside of            
                // it this class can end up re-sorting on alternate cell updates -
                // which can be a performance problem for large tables. The last
                // clause avoids this problem.
                int column = e.getColumn();
                if (e.getFirstRow() == e.getLastRow()
                        && column != TableModelEvent.ALL_COLUMNS
                        && getSortingStatus(column) == NOT_SORTED
                        && modelToView != null) {
                    int viewIndex = getModelToView()[e.getFirstRow()];
                    fireTableChanged(new TableModelEvent(TableSorter.this,
                                                         viewIndex, viewIndex,
                                                         column, e.getType()));
                    return;
                // Something has happened to the data that may have invalidated the row order.
                clearSortingState();
                fireTableDataChanged();
                return;
        private class MouseHandler extends MouseAdapter {
            public void mouseClicked(MouseEvent e) {
                JTableHeader h = (JTableHeader) e.getSource();
                TableColumnModel columnModel = h.getColumnModel();
                int viewColumn = columnModel.getColumnIndexAtX(e.getX());
                int column = columnModel.getColumn(viewColumn).getModelIndex();
                if (column != -1) {
                    int status = getSortingStatus(column);
                    if (!e.isControlDown()) {
                        cancelSorting();
                    // Cycle the sorting states through {NOT_SORTED, ASCENDING, DESCENDING} or
                    // {NOT_SORTED, DESCENDING, ASCENDING} depending on whether shift is pressed.
                    status = status + (e.isShiftDown() ? -1 : 1);
                    status = (status + 4) % 3 - 1; // signed mod, returning {-1, 0, 1}
                    setSortingStatus(column, status);
        private static class Arrow implements Icon {
            private boolean descending;
            private int size;
            private int priority;
            public Arrow(boolean descending, int size, int priority) {
                this.descending = descending;
                this.size = size;
                this.priority = priority;
            public void paintIcon(Component c, Graphics g, int x, int y) {
                Color color = c == null ? Color.GRAY : c.getBackground();            
                // In a compound sort, make each succesive triangle 20%
                // smaller than the previous one.
                int dx = (int)(size/2*Math.pow(0.8, priority));
                int dy = descending ? dx : -dx;
                // Align icon (roughly) with font baseline.
                y = y + 5*size/6 + (descending ? -dy : 0);
                int shift = descending ? 1 : -1;
                g.translate(x, y);
                // Right diagonal.
                g.setColor(color.darker());
                g.drawLine(dx / 2, dy, 0, 0);
                g.drawLine(dx / 2, dy + shift, 0, shift);
                // Left diagonal.
                g.setColor(color.brighter());
                g.drawLine(dx / 2, dy, dx, 0);
                g.drawLine(dx / 2, dy + shift, dx, shift);
                // Horizontal line.
                if (descending) {
                    g.setColor(color.darker().darker());
                } else {
                    g.setColor(color.brighter().brighter());
                g.drawLine(dx, 0, 0, 0);
                g.setColor(color);
                g.translate(-x, -y);
            public int getIconWidth() {
                return size;
            public int getIconHeight() {
                return size;
        private class SortableHeaderRenderer implements TableCellRenderer {
            private TableCellRenderer tableCellRenderer;
            public SortableHeaderRenderer(TableCellRenderer tableCellRenderer) {
                this.tableCellRenderer = tableCellRenderer;
            public Component getTableCellRendererComponent(JTable table,
                                                           Object value,
                                                           boolean isSelected,
                                                           boolean hasFocus,
                                                           int row,
                                                           int column) {
                Component c = tableCellRenderer.getTableCellRendererComponent(table,
                        value, isSelected, hasFocus, row, column);
                if (c instanceof JLabel) {
                    JLabel l = (JLabel) c;
                    l.setHorizontalTextPosition(JLabel.LEFT);
                    int modelColumn = table.convertColumnIndexToModel(column);
                    l.setIcon(getHeaderRendererIcon(modelColumn, l.getFont().getSize()));
                return c;
        private static class Directive {
            private int column;
            private int direction;
            public Directive(int column, int direction) {
                this.column = column;
                this.direction = direction;
    }

    The table listens to the TableModel for changes. Changing the table by adding/removing
    rows or columns has no affect on its table model. If you make changes to the table model
    the table will be notified by its TableModelListener and change its view. So tell
    MyTableModel about the change of data:
    public class TableSorterDemo implements ActionListener
        MyTableModel tableModel;
        public TableSorterDemo()
            defaultListModel = new DefaultListModel();
            init1();
            tableModel = new MyTableModel(defaultListModel);
            TableSorter sorter = new TableSorter(tableModel);
        public void actionPerformed(ActionEvent ae)
            if (ae.getSource()==clickMe)
                defaultListModel.removeAllElements();
                init2();
                tableModel.fireTableStructureChanged();
    }

  • Can't sort files and folders

    Two questions:
    1. In a folder I want to sort the items in order allways folders first and second files by namne but sometimes the folders last. Is it any way to solve this? The Mac mixed sorting makes me mad.
    2. When in Finder-menu View the choice Clean Up and Arrange by is grey and can't be used. How come? Is it possible to make these choices active?
    Svante

    It's always frustrating when the designers didn't think to do it 'your' way. But we all figured out how to drive cars that were built 'their' way and we can do this too. The fact that MicroSoft did it another way, just is not relevant to working with your Mac. We're still coping with sillyunderscoresover here, and now our apps quit on us when we close their windows.
    You like a hierarchy that puts folders before individual file items: Make a folder, call it "Directories" (or even better " Directories", or "•Folders"), put all your folders in that window into it, and if you want, make a companion "Documents" folder for everything else. Click the flippy triangles of both to reveal their contents. There, everything in list order, folders first. You will have to do a teensy bit of handfiling you're not used to, but as others mentioned a simple naming convention would have spared you that (and this suggestion). If you truly hate the look, you can make invisible custom icons for the two folders and use a style like:"••••••Folders•••••", "-----Files----" so they look like headers.
    People have complained about missing this Windows 'feature' before without ever convincing me of its virtue. I can see which items are folders and don't need them artificially at the top (Sort by kind does that if ever I do) and find the integrated alphanumeric list useful for grouping unfiled documents near their folders. When I want the first item(s) on the list to be a folder, I so name it. You can cope, just like you can learn to navigate a new subdivision with all the cul-de-sacs. Now if I could just get used to this silly idea North Americans have that we should drive on the right.
    Message was edited by: Ed Hanna
    Message was edited by: Ed Hanna

  • Can't sort files and folders. Sorry doubble mailed

    Two questions:
    1. In a folder I want to sort the items in order allways folders first and second files by namne but sometimes the folders last. Is it any way to solve this? The Mac mixed sorting makes me mad.
    2. When in Finder-menu View the choice Clean Up and Arrange by is grey and can't be used. How come? Is it possible to make these choices active?
    Svante
    Message was edited by: Svante

    It's always frustrating when the designers didn't think to do it 'your' way. But we all figured out how to drive cars that were built 'their' way and we can do this too. The fact that MicroSoft did it another way, just is not relevant to working with your Mac. We're still coping with sillyunderscoresover here, and now our apps quit on us when we close their windows.
    You like a hierarchy that puts folders before individual file items: Make a folder, call it "Directories" (or even better " Directories", or "•Folders"), put all your folders in that window into it, and if you want, make a companion "Documents" folder for everything else. Click the flippy triangles of both to reveal their contents. There, everything in list order, folders first. You will have to do a teensy bit of handfiling you're not used to, but as others mentioned a simple naming convention would have spared you that (and this suggestion). If you truly hate the look, you can make invisible custom icons for the two folders and use a style like:"••••••Folders•••••", "-----Files----" so they look like headers.
    People have complained about missing this Windows 'feature' before without ever convincing me of its virtue. I can see which items are folders and don't need them artificially at the top (Sort by kind does that if ever I do) and find the integrated alphanumeric list useful for grouping unfiled documents near their folders. When I want the first item(s) on the list to be a folder, I so name it. You can cope, just like you can learn to navigate a new subdivision with all the cul-de-sacs. Now if I could just get used to this silly idea North Americans have that we should drive on the right.
    Message was edited by: Ed Hanna
    Message was edited by: Ed Hanna

  • Problem in capturing the edited data while the table is sorted

    hi,
    i am using the TableSorter class provided by the sun tutorials to add sorting capability for my JTable. i need to print on the screen, the value of the cell whenever it is updated. so i am using TableModelListener and its tableChanged() method for this purpose. if i edit the data without applying the sorting then its printing fine. But if i edit the data with table sorted in a particular order by clicking on the table header then the tableChanged method is not being called. So some problem lies in the table sorter which is preventing the call to the tableChanged method whenver table it is sorted. Below is my implementation of JTable.
    TableSorter sorter = new TableSorter(new MyTableModel());
    final JTable table = new JTable(sorter);
    table.getModel().addTableModelListener(new
    TableModelListener()
         public void tableChanged(TableModelEvent e)
              int row = e.getFirstRow();
                                               int column = e.getColumn();
              System.out.println("Row: "+row+" Coloumn:  "+column);
    );Hope u understood the problem. plzz help
    thanx

    hi camickr,
    However the row number displayed is always the row of
    the TableModel before the data has been sorted. this is the feature i am trying for and couldnt achieve it. i do want to print the row of tablemodel before data is sorted but i am getting 0 and -1 as row and column numbers.
    I never saw -1 as a column number.
    if you have never seen -1 as column number then just compile and run the code given below. I just added a table model listener to the table model to capture data editing. So if u edit any cell without applying sorting then its row and column number is printed properly but if u sort a particlar column and with sorting on if u edit any cell you will get row No. as 0 and column No. as -1. try running below code and please let me know where the problem exists or post your code which worked without any of the above problems.
    I believe the code was updated in Feb of this year,
    so make sure you have the most recent version.yes i have the latest version of tablesorter.
    below is my source code for table sorting just compile and run it
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.sql.*;
    import javax.swing.table.*;
    import java.util.*;
    class TableSorterDemo extends JFrame
         public TableSorterDemo()
         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         TableSorter sorter=new TableSorter(new MyTableModel());
         JTable table=new JTable(sorter);
         sorter.setTableHeader(table.getTableHeader());
         table.getModel().addTableModelListener(new
    TableModelListener()
         public void tableChanged(TableModelEvent e)
              int row = e.getFirstRow();
            int column = e.getColumn();
              System.out.println("Row :"+row+" Column: "+column);
         JScrollPane scrollPane = new JScrollPane(table);
         scrollPane.setBackground(new Color(198,232,189));
         add(scrollPane);
         pack();
         setVisible(true);
          class MyTableModel extends AbstractTableModel {
            final String[] columnNames = {"First Name",
                                          "Last Name",
                                          "Sport",
                                          "# of Years",
                                          "Vegetarian"};
            final Object[][] data = {
                {"Mary", "Campione",
                 "Snowboarding", new Integer(5), new Boolean(false)},
                {"Alison", "Huml",
                 "Rowing", new Integer(3), new Boolean(true)},
                {"Kathy", "Walrath",
                 "Chasing toddlers", new Integer(2), new Boolean(false)},
                {"Sharon", "Zakhour",
                 "Speed reading", new Integer(20), new Boolean(true)},
                {"Angela", "Lih",
                 "Teaching high school", new Integer(4), new Boolean(false)}
            public int getColumnCount() {
                return columnNames.length;
            public int getRowCount() {
                return data.length;
            public String getColumnName(int col) {
                return columnNames[col];
            public Object getValueAt(int row, int col) {
                return data[row][col];
             * JTable uses this method to determine the default renderer/
             * editor for each cell.  If we didn't implement this method,
             * then the last column would contain text ("true"/"false"),
             * rather than a check box.
            public Class getColumnClass(int c) {
                return getValueAt(0, c).getClass();
             * Don't need to implement this method unless your table's
             * editable.
            public boolean isCellEditable(int row, int col) {
                //Note that the data/cell address is constant,
                //no matter where the cell appears onscreen.
                if (col < 2) {
                    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) {
                    data[row][col] = value;
                    fireTableCellUpdated(row, col);
                   //     System.out.println("row "+row+"Col "+col+"Val "+value);
         public static void main(String[] args)
         new TableSorterDemo();
       /*Table Sorter Class*/
    class TableSorter extends AbstractTableModel {
        protected TableModel tableModel;
        public static final int DESCENDING = -1;
        public static final int NOT_SORTED = 0;
        public static final int ASCENDING = 1;
        private static Directive EMPTY_DIRECTIVE = new Directive(-1, NOT_SORTED);
        public static final Comparator COMPARABLE_COMAPRATOR = new Comparator() {
            public int compare(Object o1, Object o2) {
                return ((Comparable) o1).compareTo(o2);
        public static final Comparator LEXICAL_COMPARATOR = new Comparator() {
            public int compare(Object o1, Object o2) {
                return o1.toString().compareTo(o2.toString());
        private Row[] viewToModel;
        private int[] modelToView;
        private JTableHeader tableHeader;
        private MouseListener mouseListener;
        private TableModelListener tableModelListener;
        private Map columnComparators = new HashMap();
        private java.util.List sortingColumns = new ArrayList();
        public TableSorter() {
            this.mouseListener = new MouseHandler();
            this.tableModelListener = new TableModelHandler();
        public TableSorter(TableModel tableModel) {
            this();
            setTableModel(tableModel);
        public TableSorter(TableModel tableModel, JTableHeader tableHeader) {
            this();
            setTableHeader(tableHeader);
            setTableModel(tableModel);
        private void clearSortingState() {
            viewToModel = null;
            modelToView = null;
        public TableModel getTableModel() {
            return tableModel;
        public void setTableModel(TableModel tableModel) {
            if (this.tableModel != null) {
                this.tableModel.removeTableModelListener(tableModelListener);
            this.tableModel = tableModel;
            if (this.tableModel != null) {
                this.tableModel.addTableModelListener(tableModelListener);
            clearSortingState();
            fireTableStructureChanged();
        public JTableHeader getTableHeader() {
            return tableHeader;
        public void setTableHeader(JTableHeader tableHeader) {
            if (this.tableHeader != null) {
                this.tableHeader.removeMouseListener(mouseListener);
                TableCellRenderer defaultRenderer = this.tableHeader.getDefaultRenderer();
                if (defaultRenderer instanceof SortableHeaderRenderer) {
                    this.tableHeader.setDefaultRenderer(((SortableHeaderRenderer) defaultRenderer).tableCellRenderer);
            this.tableHeader = tableHeader;
            if (this.tableHeader != null) {
                this.tableHeader.addMouseListener(mouseListener);
                this.tableHeader.setDefaultRenderer(
                        new SortableHeaderRenderer(this.tableHeader.getDefaultRenderer()));
        public boolean isSorting() {
            return sortingColumns.size() != 0;
        private Directive getDirective(int column) {
            for (int i = 0; i < sortingColumns.size(); i++) {
                Directive directive = (Directive)sortingColumns.get(i);
                if (directive.column == column) {
                    return directive;
            return EMPTY_DIRECTIVE;
        public int getSortingStatus(int column) {
            return getDirective(column).direction;
        private void sortingStatusChanged() {
            clearSortingState();
            fireTableDataChanged();
            if (tableHeader != null) {
                tableHeader.repaint();
        public void setSortingStatus(int column, int status) {
            Directive directive = getDirective(column);
            if (directive != EMPTY_DIRECTIVE) {
                sortingColumns.remove(directive);
            if (status != NOT_SORTED) {
                sortingColumns.add(new Directive(column, status));
            sortingStatusChanged();
        protected Icon getHeaderRendererIcon(int column, int size) {
            Directive directive = getDirective(column);
            if (directive == EMPTY_DIRECTIVE) {
                return null;
            return new Arrow(directive.direction == DESCENDING, size, sortingColumns.indexOf(directive));
        private void cancelSorting() {
            sortingColumns.clear();
            sortingStatusChanged();
        public void setColumnComparator(Class type, Comparator comparator) {
            if (comparator == null) {
                columnComparators.remove(type);
            } else {
                columnComparators.put(type, comparator);
        protected Comparator getComparator(int column) {
            Class columnType = tableModel.getColumnClass(column);
            Comparator comparator = (Comparator) columnComparators.get(columnType);
            if (comparator != null) {
                return comparator;
            if (Comparable.class.isAssignableFrom(columnType)) {
                return COMPARABLE_COMAPRATOR;
            return LEXICAL_COMPARATOR;
        private Row[] getViewToModel() {
            if (viewToModel == null) {
                int tableModelRowCount = tableModel.getRowCount();
                viewToModel = new Row[tableModelRowCount];
                for (int row = 0; row < tableModelRowCount; row++) {
                    viewToModel[row] = new Row(row);
                if (isSorting()) {
                    Arrays.sort(viewToModel);
            return viewToModel;
        public int modelIndex(int viewIndex) {
            return getViewToModel()[viewIndex].modelIndex;
        private int[] getModelToView() {
            if (modelToView == null) {
                int n = getViewToModel().length;
                modelToView = new int[n];
                for (int i = 0; i < n; i++) {
                    modelToView[modelIndex(i)] = i;
            return modelToView;
        // TableModel interface methods
        public int getRowCount() {
            return (tableModel == null) ? 0 : tableModel.getRowCount();
        public int getColumnCount() {
            return (tableModel == null) ? 0 : tableModel.getColumnCount();
        public String getColumnName(int column) {
            return tableModel.getColumnName(column);
        public Class getColumnClass(int column) {
            return tableModel.getColumnClass(column);
        public boolean isCellEditable(int row, int column) {
            return tableModel.isCellEditable(modelIndex(row), column);
        public Object getValueAt(int row, int column) {
            return tableModel.getValueAt(modelIndex(row), column);
        public void setValueAt(Object aValue, int row, int column) {
            tableModel.setValueAt(aValue, modelIndex(row), column);
        // Helper classes
        private class Row implements Comparable {
            private int modelIndex;
            public Row(int index) {
                this.modelIndex = index;
            public int compareTo(Object o) {
                int row1 = modelIndex;
                int row2 = ((Row) o).modelIndex;
                for (Iterator it = sortingColumns.iterator(); it.hasNext();) {
                    Directive directive = (Directive) it.next();
                    int column = directive.column;
                    Object o1 = tableModel.getValueAt(row1, column);
                    Object o2 = tableModel.getValueAt(row2, column);
                    int comparison = 0;
                    // Define null less than everything, except null.
                    if (o1 == null && o2 == null) {
                        comparison = 0;
                    } else if (o1 == null) {
                        comparison = -1;
                    } else if (o2 == null) {
                        comparison = 1;
                    } else {
                        comparison = getComparator(column).compare(o1, o2);
                    if (comparison != 0) {
                        return directive.direction == DESCENDING ? -comparison : comparison;
                return 0;
        private class TableModelHandler implements TableModelListener {
            public void tableChanged(TableModelEvent e) {
                // If we're not sorting by anything, just pass the event along.            
                if (!isSorting()) {
                    clearSortingState();
                    fireTableChanged(e);
                    return;
                if (e.getFirstRow() == TableModelEvent.HEADER_ROW) {
                    cancelSorting();
                    fireTableChanged(e);
                    return;
                int column = e.getColumn();
                if (e.getFirstRow() == e.getLastRow()
                        && column != TableModelEvent.ALL_COLUMNS
                        && getSortingStatus(column) == NOT_SORTED
                        && modelToView != null) {
                    int viewIndex = getModelToView()[e.getFirstRow()];
                    fireTableChanged(new TableModelEvent(TableSorter.this,
                                                         viewIndex, viewIndex,
                                                         column, e.getType()));
                    return;
                // Something has happened to the data that may have invalidated the row order.
                clearSortingState();
                fireTableDataChanged();
                return;
        private class MouseHandler extends MouseAdapter {
            public void mouseClicked(MouseEvent e) {
                JTableHeader h = (JTableHeader) e.getSource();
                TableColumnModel columnModel = h.getColumnModel();
                int viewColumn = columnModel.getColumnIndexAtX(e.getX());
                int column = columnModel.getColumn(viewColumn).getModelIndex();
                if (column != -1) {
                    int status = getSortingStatus(column);
                    if (!e.isControlDown()) {
                        cancelSorting();
                    // Cycle the sorting states through {NOT_SORTED, ASCENDING, DESCENDING} or
                    // {NOT_SORTED, DESCENDING, ASCENDING} depending on whether shift is pressed.
                    status = status + (e.isShiftDown() ? -1 : 1);
                    status = (status + 4) % 3 - 1; // signed mod, returning {-1, 0, 1}
                    setSortingStatus(column, status);
        private static class Arrow implements Icon {
            private boolean descending;
            private int size;
            private int priority;
            public Arrow(boolean descending, int size, int priority) {
                this.descending = descending;
                this.size = size;
                this.priority = priority;
            public void paintIcon(Component c, Graphics g, int x, int y) {
                Color color = c == null ? Color.GRAY : c.getBackground();            
                // In a compound sort, make each succesive triangle 20%
                // smaller than the previous one.
                int dx = (int)(size/2*Math.pow(0.8, priority));
                int dy = descending ? dx : -dx;
                // Align icon (roughly) with font baseline.
                y = y + 5*size/6 + (descending ? -dy : 0);
                int shift = descending ? 1 : -1;
                g.translate(x, y);
                // Right diagonal.
                g.setColor(color.darker());
                g.drawLine(dx / 2, dy, 0, 0);
                g.drawLine(dx / 2, dy + shift, 0, shift);
                // Left diagonal.
                g.setColor(color.brighter());
                g.drawLine(dx / 2, dy, dx, 0);
                g.drawLine(dx / 2, dy + shift, dx, shift);
                // Horizontal line.
                if (descending) {
                    g.setColor(color.darker().darker());
                } else {
                    g.setColor(color.brighter().brighter());
                g.drawLine(dx, 0, 0, 0);
                g.setColor(color);
                g.translate(-x, -y);
            public int getIconWidth() {
                return size;
            public int getIconHeight() {
                return size;
        private class SortableHeaderRenderer implements TableCellRenderer {
            private TableCellRenderer tableCellRenderer;
            public SortableHeaderRenderer(TableCellRenderer tableCellRenderer) {
                this.tableCellRenderer = tableCellRenderer;
            public Component getTableCellRendererComponent(JTable table,
                                                           Object value,
                                                           boolean isSelected,
                                                           boolean hasFocus,
                                                           int row,
                                                           int column) {
                Component c = tableCellRenderer.getTableCellRendererComponent(table,
                        value, isSelected, hasFocus, row, column);
                if (c instanceof JLabel) {
                    JLabel l = (JLabel) c;
                    l.setHorizontalTextPosition(JLabel.LEFT);
                    int modelColumn = table.convertColumnIndexToModel(column);
                    l.setIcon(getHeaderRendererIcon(modelColumn, l.getFont().getSize()));
                return c;
        private static class Directive {
            private int column;
            private int direction;
            public Directive(int column, int direction) {
                this.column = column;
                this.direction = direction;
    }

  • Help in AS3 Sprite

    Hello All,
    I got this Error : 1061: Call to a possibly undefined method addChild through a reference with static type Class.
    what I'm trying to do :
    I have create a new class called Graph and make it extends Sprite and  add a scroolpane to my stage and make an empty movie clip called content_mc and make the source of the scrollpane equals to content_mc
    in the first frame i wrote this code
    import Graph;
    var graph:Graph = new Graph();
    content_mc.addChild(graph);
    Any help will be appreciated
    Thanks in Advance

    Thanks for your reply
    I did what you say , but I still have the same error
    and I have create the content_mc
    insert-> new symbol -> Enter the name of content_mc -> choose the option export fpr actionscript and then click ok
    and I have creating some shapes in it and test it with the scrollpane and it's working
    but when i remove the shapes and use the action script to add an inistance from my graph to it i have the previous error
    Thanks in Advance

  • Radix Sort - Examining digits

    Hey guys, is there a way to examine the "X" digit within an element of an array? Example:
    nums[0] = 234
    nums[1] = 96
    nums[2] = 436
    nums[3] = 150
    If I wanted to find the "one's" digit in nums[0], how would I do it? We can obviously see that the digit is "4," but I need a way for the program to recognize that, and store it into a variable. Thanks in advance.

    Perhaps I should clarify my problem. Here is the full briefing.
    I need to use Radix Sort to order a list of positive integers. A Radix Sort makes as many passe through the list as there are digits in the largest number to be sorted. For example, if the largest integer in the list were 492, then the algorithm would make three passes through the list to sort it.
    In each pass through the list, the Radix Sort algorithm sorts the numbers based on a different digit, working from the least to the most significant digit. To do this, it uses an intermediate data strucutre, ques, an array of ten queues. Each number is placed into the queu corresponding to the value of the digit being examined. For example, in the first pass the digit in the one's place is considered, so the number 345 would be enqueued into ques[5]. The number 260 would be enqueed into ques[0]. In each pass, the algorithm moves the numbers to be sorted from the list to the array of queues and then back to the list,. After the last pass, the integers are in order, from smallest to largest.
    ]Step 1
    Taking each integer in the list in order, insert the integer into the queue corresponding to the value of the digit currently being examined. If the integer being examined does not have a digit at a given place value, 0 is assumed for that place value. For example, 95 has no digit in the hundred's place, so, when examining the hundred's digit, the algorithm would assume the value in the hundred's place is zero and enqueue 95 into ques[0].
    Step 2
    After all integers have been inserted into the appropriate queues, each queue is emptied in order into the array, starting with ques[0].
    For example, assume that array numbs contain the integers 380, 95, 345, 382, 260, 100, and 492. The sort will take three passes, because the largest integer in the array has 3 digits.
    Here is an example diagram.
    Pass I   (Examines the FIRST DIGIT, AKA "one's" digit)
    Nums Before Pass                                                                                 Nums After Pass
                                                               ques
    [0] 380                                                     [0]   380   260   100                                [0] 380
    [1] 95                                                       [1]                                                           [1] 260
    [2] 345                                                     [2]   382  492                                          [2] 100
    [3] 382                                                     [3]                                                           [3] 382
    [4] 250                                                     [4]                                                           [4] 492
    [5] 100                                                     [5]   95   345                                           [5] 95
    [6] 492                                                     [6]                                                           [6] 345
                                                                     ...goes all the way to [9]That is an example of Pass I.
    So my question is, how the heck do I examine only the first digit? I know how to find the maximum amount of digits, and I know how to sort it once I get them into the queues. However, I have no clue as to find out the individual one's, ten's, hundreds digit so that I can organize them into the queue. Thanks in advance.

  • Can a sprite become visible after a certain amount of user inactivity?

    Can a sprite become visible after a certain amount of user inactivity? like a timer triggering an event?

    Hi Kevin,
    You can look at the on timeOut event. (This is not to be confused with timeOut objects)
    There are a number of related properties, which date back from the early days of Director, and which seem to have been omitted from recent versions of the documentation, even though they still function. I give them here with their original names (prior to Director 10):
    the timeOutKeyDown
    the timeOutLapsed
    the timeOutLength
    the timeOutMouse
    the timeOutPlay
    the timeOutScript
    the lastClick
    the lastEvent
    the lastKey
    the lastRoll
    (You can also use the more recent DOM style for these last four properties: _player.lastXXX)
    Here's a very simple script which will make sprite 1 disappear when the movie starts, and reappear if the user does nothing for 5 seconds:
    on startMovie()
      sprite(1).visible = FALSE
      the timeOutLength = 300 -- = 5 seconds * 60 ticks / second
    end startMovie
    on timeOut()
      sprite(1).visible = TRUE
    end timeOut
    If you click the mouse at intervals of less than 5 seconds after starting the movie, then the sprite will remain invisible.
    NOTE: Using sprite(x).visible = FALSE will make the entire sprite channel invisible everywhere in the Score. It's better to use sprite(x).blend = 0, unless the sprite must not react to the mouse while it is invisble, in which case it is better to move it off-stage.
    Is this what you are looking for?
    James

Maybe you are looking for

  • How to change NLS_NUMERIC_CHARACTERS parameter for OWB SQLLDR mapping

    Hi, How to change the NLS_NUMERIC_CHARACTERS database paramater for my SQLLDR mapping? I have an input flat file which has numeric data with ',' as decimal separator means NLS_NUMERIC_CHARACTERS setting as ',.' However in my target oracle schema, the

  • The memory could not be "read" - FRM-92101

    Hi: I tried to copy the records from one block(database) to the other(non-database). It's working fine when the block had less than 50 records. But when it's greater than 50 records I got the following errors: ifweb90.exe - Application Error The inst

  • Recording audio from iPad to Mac

    I have an iPad app that allows you to download different audio presentations.  However, the audio is trapped in the iPad app, which means I can't listen to it anywhere but the iPad.  I'd like to transfer this audio to an MP3 so I can listen to it on

  • Import ics into Calendar, getting error 403...

    I have been getting this issues since upgrading two weeks ago to Yosemite. Every invitation I get from my work colleagues end with this continuous error. It means I am constantly cancelling the errors for each invitation continuously all day. The ser

  • Is there a supported flash player ? I need it to get on some websites !

    I need to get on a few websites that require flash player. Is there a supported one for my ipad2?