Avoid iterating through everything

Hello all,
Hope you guys can help me with this problem. I have a program that draws anywhere from 1-300,000 letters on a canvas. Each letter is created from a class called StringState which extends Rectangle. What I would like to do is have each letter respond when the user moves the mouse over the letter by growing bigger. I figured I can just see if the letters bounds contains the point where the mouse moved to and if it does change the letters size and repaint around that letter to update the display. This works great from 1-5000 letters but getting up to 10,000 or even higher creates a very visible lag while the program is iterating through the letters to check if the mouse location intersects the letters bounds. What I was wondering is there a way to get this result without iterating through the entire collection of letters to see if it contains the mouse location? Like can I attach some kind of mouse listener to each letter or something like that? The following program just demonstrates how I create and display the letters I haven't really had a chance to create a demonstration of how they would grow when hovered over. The program i'm working on that actually demonstrates this is very large and hard to trim down to show an example so the following code is actually from a previous question I asked and was provided by Aephyr. Thanks in advance for your guys help :)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.util.List;
public class PaintSurface implements Runnable, ActionListener {
     public static void main(String[] args) {
          SwingUtilities.invokeLater(new PaintSurface());
     Tableaux tableaux;
     Random random = new Random();
//        Point mouselocation = new Point(0,0);
     static final int WIDTH = 1000;
     static final int HEIGHT = 1000;
        JFrame frame = new JFrame();
     public void run() {
          tableaux = new Tableaux();
          for (int i=15000; --i>=0;)
               addRandom();
          frame.add(tableaux, BorderLayout.CENTER);
          JButton add = new JButton("Add");
          add.addActionListener(this);
          frame.add(add, BorderLayout.SOUTH);
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.setSize(WIDTH, HEIGHT);
          frame.setLocationRelativeTo(null);
//                frame.addMouseMotionListener(new MouseListener());
          frame.setVisible(true);
     public void actionPerformed(ActionEvent e) {
          addRandom();
     void addRandom() {
          tableaux.add(
                    Character.toString((char)('a'+random.nextInt(26))),
                    UIManager.getFont("Button.font"),
                    random.nextInt(WIDTH), random.nextInt(HEIGHT));
//        class MouseListener extends MouseAdapter {
//            public void mouseMoved(MouseEvent e) {
//                mouselocation = new Point(e.getX(),e.getY());
//                frame.repaint();
        class StringState extends Rectangle {
                StringState(String str, Font font, int x, int y, int w, int h) {
                        super(x, y, w, h);
                        string = str;
                        this.font = font;
                String string;
                Font font;
        class Tableaux extends JComponent {
             Tableaux() {
                  this.enableEvents(MouseEvent.MOUSE_MOTION_EVENT_MASK);
                  lagState = createState("Lag", new Font("Arial",Font.BOLD,20), 0, 0);
             protected void processMouseMotionEvent(MouseEvent e) {
                  repaint(lagState);
                  lagState.setLocation(e.getX(), e.getY());
                  repaint(lagState);
                  super.processMouseMotionEvent(e);
             StringState lagState;
                List<StringState> states = new ArrayList<StringState>();
                StringState createState(String str, Font font, int x, int y) {
                    FontMetrics metrics = getFontMetrics(font);
                    int w = metrics.stringWidth(str);
                    int h = metrics.getHeight();
                    return new StringState(str, font, x, y-metrics.getAscent(), w, h);
                public void add(String str, Font font, int x, int y) {
                     StringState state = createState(str, font, x, y);
                        states.add(state);
                        repaint(state);
                protected void paintComponent(Graphics g) {
                        Rectangle clip = g.getClipBounds();
                        FontMetrics metrics = g.getFontMetrics();
                        for (StringState state : states) {
                                if (state.intersects(clip)) {
                                        if (!state.font.equals(g.getFont())) {
                                                g.setFont(state.font);
                                                metrics = g.getFontMetrics();
                                        g.drawString(state.string, state.x, state.y+metrics.getAscent());
                        if (lagState.intersects(clip)) {
                        g.setColor(Color.red);
                        if (!lagState.font.equals(g.getFont())) {
                            g.setFont(lagState.font);
                            metrics = g.getFontMetrics();
                        g.drawString("Lag", lagState.x, lagState.y+metrics.getAscent());
}Here is the code that iterates through the letters to see if a letter contains the mouse location:
            if(e.getSource()==canvas&&edit) {
                for(Letter l : letters) {
                    Rectangle rec = new Rectangle(l.x+l.xoffset,l.y+l.yoffset,l.width,l.height);
                    if(rec.contains(new Point(e.getX(),e.getY()))&&l.resizing==false&&l.defaultSize==l.font.getSize()) {
                        l.resizing = true;
                        new Thread(new ExpandLetter(l)).start();
                    else if(!rec.contains(new Point(e.getX(),e.getY()))&&l.resizing==false){
                        l.font = new Font(l.font.getName(),l.font.getStyle(),l.defaultSize);
                        l.resizeLetter(l.text);
            }However I just learned that this loop itself is taking up a huge amount of memory by saying
l.font = new Font(l.font.getName(),l.font.getStyle(),l.defaultSize); When I take that line out the lag is reduced by a lot. Also I think that it isn't forgetting the "old" letters font that it is replacing by saying new Font() and after running this loop once my program runs slow and laggy as if it doesn't have enough memory to run fast anymore. Is there something I am doing wrong by initiating a new Font. I would have thought that it wouldn't take up anymore memory because it replaces the old font the the letter "l" has. The loop seems to have some kind of memory leak if someone could point it out to me that would be great. Thanks :)
Edited by: neptune692 on Feb 16, 2010 8:18 PM

neptune692 wrote:
can I attach some kind of mouse listener to each letterTry this:
import java.awt.*;
import java.awt.event.*;
import java.awt.font.*;
import java.awt.geom.*;
import javax.swing.*;
import java.util.*;
import javax.swing.event.*;
public class SimplePaintSurface implements Runnable, ActionListener {
    private static final int WIDTH = 1250;
    private static final int HEIGHT = 800;
    private Random random = new Random();
    private JFrame frame = new JFrame("SimplePaintSurface");
    private JPanel tableaux;
    public void run() {
        tableaux = new JPanel(null);
        for (int i = 15000; --i >= 0;) {
            addRandom();
        frame.add(tableaux, BorderLayout.CENTER);
        JButton add = new JButton("Add");
        add.addActionListener(this);
        frame.add(add, BorderLayout.SOUTH);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(WIDTH, HEIGHT);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        tableaux.requestFocusInWindow();
    public void actionPerformed(final ActionEvent e) {
        addRandom();
        tableaux.repaint();
    void addRandom() {
        Letter letter = new Letter(Character.toString((char) ('a' + random.nextInt(26))));
        letter.setBounds(random.nextInt(WIDTH), random.nextInt(HEIGHT), 16, 16);
        tableaux.add(letter);
    public static void main(final String[] args) {
        SwingUtilities.invokeLater(new SimplePaintSurface());
class Letter extends JLabel {
    Font font1;
    Font font2;
    private final FontRenderContext fontRenderContext1;
    private final FontRenderContext fontRenderContext2;
    public Letter(final String letter) {
        super(letter);
        setFocusable(true);
        setBackground(Color.RED);
        font1 = getFont();
        font2 = font1.deriveFont(48f);
        fontRenderContext1 = getFontMetrics(font1).getFontRenderContext();
        fontRenderContext2 = getFontMetrics(font2).getFontRenderContext();
        MouseInputAdapter mouseHandler = new MouseInputAdapter() {
            @Override
            public void mouseEntered(final MouseEvent e) {
                Letter.this.setOpaque(true);
                setFont(font2);
                Rectangle bounds = getBounds();
                Rectangle2D stringBounds = font2.getStringBounds(getText(), fontRenderContext2);
                bounds.width = (int) stringBounds.getWidth();
                bounds.height = (int) stringBounds.getHeight();
                setBounds(bounds);
            @Override
            public void mouseExited(final MouseEvent e) {
                Letter.this.setOpaque(false);
                setFont(font1);
                Rectangle bounds = getBounds();
                Rectangle2D stringBounds = font1.getStringBounds(getText(), fontRenderContext1);
                bounds.width = (int) stringBounds.getWidth();
                bounds.height = (int) stringBounds.getHeight();
                setBounds(bounds);
        addMouseListener(mouseHandler);
}

Similar Messages

  • Hi I have 2 apple id's one which has pulled through everything except my calendars and one which has pulled through just my calendars. How do I move my calendars from one apple id to another?

    Hi I have 2 apple id's one which has pulled through everything into icloud except my calendars and one which has pulled through just my calendars. How do I move my calendars from one apple id to another so that I can see everything in icloud with one apple id?

    Having read some other posts I think I have answered my question. If I was somehow able to terminate my old (unwanted) account and Apple ID I would no longer be able to access the material I bought with that ID-  so I'm stuck. I have to learn how to manage that situation.
    This is unfortunate for Apple consumers. Life is complicated for families these days and this "rule" although it is in place to prevent cheating and fraud makes things unnnecessarily difficult for me and my family as in my niaevity (sic) with the online world I bumbled into this situation. Not everyone is out to rip off Apple - one of the worlds richest corporations- or the entertainers who market their work through iTunes.I would just like to be able to enjoy the entertainment I pay for where and when I like to on whichever computer is available to me. And I'm not terribly computer literate.   
    It would have been nice to have had the opportunity to speak just once to a real person in the employ of Apple to explain my situation to them.

  • HT4972 i am not getting notification on most of my apps, e.g twitter and facebook...except i go to the app and refreshed manually. its an iphone 4 and running on ios5...i have gone through everything and its still the same..help please........I seem to be

    i am not getting notification on most of my apps, e.g twitter and facebook...except i go to the app and refreshed manually. its an iphone 4 and running on ios5...i have gone through everything and its still the same..help please........
    I seem to be having the same problem on my brand new iPhone 4S. Everything was working fine on the phone until I updated to iOS 5.1.1, but now I no longer receive push notifications for the native Mail app, Instagram, or the Facebook app. I still seem to be receiving SMS texts and iMessages via push, but the aforementioned apps need to be opened before I can receive missed notifications (having them open in the background seems to make no difference).
    Thanks for any help that you may provide!

    did you try notifications under settings? You can customize it as per your requirement, for each application.
    check this out: http://www.gottabemobile.com/2011/10/12/ios-5-how-to-use-notification-center/ or http://reviews.cnet.com/8301-19512_7-20120625-233/ios-5-notifications-a-deeper-l ook/

  • SharePoint Online Iterating through Document Libraries CSOM

    Hi,
    I am trying to iterate though a document library and set each document/items whithin to inherit permissions (at the moment each doc/item is using uniquer permissions).
    I am able to get the specific document library that I am interesting in, however I cannot at the moment iterate though each of the items/documents within it, but here is what I have so far:
    Add-Type -Path "Libraries\Microsoft.SharePoint.Client.dll"
    Add-Type -Path "Libraries\Microsoft.SharePoint.Client.Runtime.dll"
    Add-Type -Path "Libraries\Microsoft.SharePoint.Linq.dll"
    Add-Type -Path "Libraries\Microsoft.SharePoint.dll"
    $webUrl = "https://test.sharepoint.com/sites/testsite"
    $username = "####"
    $password = "####"
    $securePass = ConvertTo-SecureString $password -AsPlainText -Force
    $listname = "TestDoc";
    $ctx = New-Object Microsoft.SharePoint.Client.ClientContext($webUrl)
    $ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username, $securePass)
    #variables
    $web = $ctx.Web
    $lists = $web.Lists
    $ctx.Load($lists)
    $ctx.Load($web)
    $ctx.ExecuteQuery()
    #print web URL
    write-host `n "Web Url:" `n $web.Url
    foreach ($list in $lists)
    if ($list.Title -eq "TestDoc")
    #print list name if found
    write-host `n "Found the list:" `n $list.Title `n
    #attempting to iterate through items in the document library
    foreach ($item2 in $list.Items)
    #list the items/documents in the document library
    write-host $item2.Title
    It is the foreach loop I am having trouble at the moment as I am not sure how to loop though each of the items/documents in the document library.
    Any suggestions on the approach I should take would be much appreciated.

    Thanks for the heads up, I have re-worked my script which is simpler and now works like a charm:
    Add-Type -Path "Libraries\Microsoft.SharePoint.Client.dll"
    Add-Type -Path "Libraries\Microsoft.SharePoint.Client.Runtime.dll"
    Add-Type -Path "Libraries\Microsoft.SharePoint.Linq.dll"
    Add-Type -Path "Libraries\Microsoft.SharePoint.dll"
    $webUrl = "https://test.sharepoint.com/sites/testsite"
    $username = "####"
    $password = "####"
    $securePass = ConvertTo-SecureString $password -AsPlainText -Force
    $listname = "TestDoc"
    $ctx = New-Object Microsoft.SharePoint.Client.ClientContext($webUrl)
    $ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username, $securePass)
    #get the List/DocLib and load it for use
    $listUpdate = $ctx.Web.Lists.GetByTitle($listname)
    $ctx.Load($listUpdate)
    $ctx.ExecuteQuery()
    #CAML Query to get all items inclusing sub-folders
    $spQuery = New-Object Microsoft.SharePoint.Client.CamlQuery
    $spQuery.ViewXml = "<View Scope='RecursiveAll' />";
    $itemki = $listUpdate.GetItems($spQuery)
    $ctx.Load($itemki)
    $ctx.ExecuteQuery()
    #iterating through the items and reseting permission inheritence
    for($j=0; $j -lt $itemki.Count; $j++)
    $itemki[$j].ResetRoleInheritance()
    $ctx.ExecuteQuery()

  • Concurrent modification exception while iterating through list

    Hi,
    I have a list of objects. I use for each loop in java to iterate through that list of objects and display them.
    The problem is that while iterating other thread can add or remove some objects from that list, and I get ConcurrentModificationException.
    How can I handle this problem. How can I be sure that I am iteration through the updated list.
    Thank you

    Synchonize on the list before iterating through it, and make sure that other code also synchronizes on the list before adding to it or removing from it. Using a list implementation that simply synchronizes all the methods (e.g. Vector) will not do that, you have to do it yourself.

  • Iterating through View Object RowIterator Bug.

    I use this code to loop through the rows of a view object (As described in javadoc of RowIteratior).
    public String checkIterations() {
    String res = "Iterated through : ";
    RowIterator view = this.getDepartmentsView1();
    view.reset();
    Row row;
    while ((row = view.next()) != null) {
    System.out.println("rownum: " + row.getAttribute("RowNum"));
    res += row.getAttribute("RowNum") + " ";
    return res;
    Yet this code never goes through the first row if the executequery has been performed for view object.
    details:
    [http://adfbugs.blogspot.com/2009/07/iterating-through-view-object.html]
    Is this a bug?
    Edited by: mkonio on Jul 28, 2009 11:41 PM

    Thanks Andrejus and Steve.
    Its a development bug
    problem and solution described in:
    Fusion Developer's Guide for Oracle ADF
    9.7.6 What You May Need to Know About Programmatic Row Set Iteration

  • Iterating through RWBTreeOnDisk

    Is there any way to Iterating through RWBTreeOnDisk, My problem is that i have 100 records in RWBTreeOnDisk and i want to fetch only first 20 records, how should i proceed to do the same, instead of getting all the records using applyToKeyAndValue(), i need to fetch particular number of records in the tree.
    Plz suggest me the way to proceed.
    Thanx

    We use sqlite for this sort of application. It gives you the power of sql but acts on files directly rather that via a server. see www.sqlite.org

  • HT1688 I just tried to install the latest software update for an iPhone 5, and now the phone is stuck in recovery mode.  Are there any options available to avoid going through with the recovery.  This seems really lame.

    I just tried to install the latest software update for an iPhone 5, and now the phone is stuck in recovery mode.  Are there any options available to avoid going through with the recovery.  This seems really lame.

    No.
    You must restore.

  • When I was setting up the language Setting, I pressed the play/pause button three times and now the voice that talks you through everything speaks extremely fast. How do I get her to speak slower?

    When I was setting up the language Setting, I pressed the play/pause button three times and now the voice that talks you through everything speaks extremely fast. How do I get her to speak slower?

    Hi Magsrobby,
    Welcome to the forum and thanks for posting. I'm really sorry to hear you've had so many problems. I can look into this for you if you wish. Drop me an email with the details. You'll find the "contact us" form in the about me section of my profile. Once I have the details we'll take it from there.
    Cheers
    David
    BTCare Community Mod
    If we have asked you to email us with your details, please make sure you are logged in to the forum, otherwise you will not be able to see our ‘Contact Us’ link within our profiles.
    We are sorry but we are unable to deal with service/account queries via the private message(PM) function so please don't PM your account info, we need to deal with this via our email account :-)

  • Iterating through a generic list of unknown type

    Hi,
    I am in the process of creating pdf reports for my project.I have to deal with a persistence api to get the data for the report.The data will be in the form of a list,like List<SomeObject>,all these lists returned by the persistence framework contains object of some type which implements a common interface.But through that interface I wont be able to get all the data for my reports.So I am looking for a generic way for iterating through the list,by providing some metadata for the data within the list. I am planning to use reflection to query through the list.Is there any feature of generic,through which I can easily iterate through this unknown type,preferrably a combination of reflection and generics,I want to reduce the LOC.Any suggestions??

    If the List returned by the framework isn't parameterized, Like
    public List<K> getList(Class<K> classType);
    then you have to cast it to the appropriate type. If you are not sure about the type of the Objects in the list, and you have a bunch of class types you could expect from the list, then you could use instanceof operator.
    If it could be Class A or B, then
    if (obj instanceof A){
    A castObject = (A) obj;
    else if(obj instanceof B){
    B castObject = (B)obj;
    }Even to do reflection to invoke methods, you need to know the method Names. Which tells me you have the knowledge of what could come out of the list. So cast them. Invoking methods using reflection is really slow.

  • Settings app has red number 1 at the top and I can't get rid off it. I have been through everything in settings eg. Turned everything off and it is still there

    Since I updated to ios5.0.1 I have had a red number one on the settings app like there is something that needs to be done. I have tried to turn everything off in settings and gone through everything one by one but cannot get rid of it.
    Any ideas?

    I have the same red number 1 on my settings app after the 5.0.1 update

  • What is the deal.  I'm trying to request service for my Ipod and everytime I go through everything and submit it, it says "Sorry we can't process your request at this time..."  I have tried numerous times and am getting very frustrated.  Please help.

    What is the deal?  I'm trying to request service for my ipod touch and every time I go through everything and submit it, it says "Sorry we can't process your request at this time..."  I'm getting very frustrated. Please help.

    Thanks for the detail.
    I believe you are doing your best, in the right place.  How long have you tried ?
    May be the sistem in your area is really busy. Can you wait few hours or contact them with a Message ?
    Or try a Service provider http://support.apple.com/kb/HT1434

  • Why do I have a constant notification on my settings? How do I get rid of it? Looked through everything and can't see why it's there

    Why do I have a constant notification on my settings? How do I get rid of it? Looked through everything and can't see why it's there

    Restore from a backup will get you some 'other' back.
    Still not happy, Restore in iTunes, Setup as new. Sync back personal data using iTunes Tabs

  • Iterating through entrys of HashMap

    I have a HashMap that is already populated. I'm iterating through the entrySet and want to get the keys and values and use them to create another object. I've searched the forum and googled but can't quite seem to find what I need. Here's the code I have so far.
    Iterator iterator = map.entrySet().iterator();
    while (iterator.hasNext()) {
    if (iterator.next() != null) {
         reasonsList.add(new DropDownData(key, value)); // here's where I'm not sure what to do
    }The DropDownData object accepts twos strings, one for the key and one for the displayed value. These strings should be the key and value from my current HashMap entry. But I can't seem to figure out how to do it.
    thanks for any help/suggestions

    iterating over the not-null entries or iteratingover
    gotten entries that are not null is equivalent,maps
    return "null" for unexisting keys...
    I do not understand what you are saying here.
    It is not required that Map implementations return "null" for non-existent keys.
    It just happens to be the way the implementations in the JDK are implemented.
    The documentation specifically says that Map.get(key) could be allowed to throw a NullPointerException.
    http://java.sun.com/j2se/1.5.0/docs/api/java/util/Map.html#get(java.lang.Object )
    >
    I would add that map's structure suggests it's the
    way to go (I mean, mine of course ;))
    That's a matter of interpretation.
    what's the point in iterating over the values when
    you need the key ?When you need the keys and the values (as in the case of the OP), then there is plenty of point in it.
    >
    the only way (the API should define) to iterate over
    a map is through the key (hence the "map" name),
    entrySet is (as far as a I reckon) a twisted bypass...It's in the API. It works well. It's useful. So there's no reason not to use it when it is applicable.

  • Iterating through List View Items using Group By and Jquery

    In my listview to my document library, I am using grouping. For each group (using month), it lists all the documents pertaining to that particular month.
    Using JQuery, I need to go through each item and parse them, but I'm having trouble finding a usable selector for the for/each function. My parsing code (JQuery) works, but since it uses the class of the table cell with a child anchor, it basically
    finds the first item and then all the subsequent file names are named the same (instead of different names, like it should be).
    Here's my current code that doesn't work (only the iteration and naming separately for each file - the parsing I'm doing seems to work):
    $(".ms-wpContentDivSpace" ).each(function( index ) {
    var val=$(".ms-vb2 a").html();
    var val2=val.replace(/_/g," ");
    $(".ms-vb2 a").html(val2);
    any ideas?

    That's because
    $(".ms-vb2 a").
    is bringing back all the pieces that have that class with an anchor on the whole page, not just the ones in the .ms-wpContentDivSpace
    I don't know the exact syntax, but I think you need to iterate through all the '.ms_vb2 a' items as well - there are multiple ones, and do something like this inside your other grouping
    $(".ms-vb2 a").each(function(index) {
        var val=$(this).html();
       var val2=val.replace(/_/g," ")
       $(this).html(val2);
    That's not quite right but maybe that will help.
    Robin

Maybe you are looking for

  • HT4623 I can't see my mail, what should I do?

    I can not see my emails. I already updated my phone up to date...could you please suggest me what to do?

  • IPhoto 8- Pictures import as black square

    Have encountered a problem when importing (2) jpg images to Iphoto 8. Images have been saved on desktop and then imported to Iphoto with result a black square. Have tried importing images to other photo albums as well as to a PC with no problem. Can

  • Vendor interest scale error !!!!

    Dear Experts At the time of executing the report through F.44 ( Vendor Interest Scale ) getting the error "Error table for vendor interest scale from 01.11.2011 No List Generated. Immediate feedback is needed. Regards, Raziq

  • Initial Load Error

    Hi All I am trying to make inital load but I am receiving the following error. But trail file has been created on target in dirdat folder about 2GB size Source and Destination windows2003 32 Bit GG version is 11.2.1.0.1 OGGCORE_11.2.1.0.1_PLATFORMS_1

  • Use of 1.5 java SE not permited in JDev 11.1.1.1

    I use JDeveloper 11.1.1.1 and I set up my preject to use java SE 1.5.0_11 . When I build the project I get in Compiler Log : Error: Project is not set up to use at least JDK 6. Why this? How can avoid this? TIA, Aurel