About a JTree of mixed String and JLabel leafs

Dear Java and Swing freaks,
Why do I get the text code instead of the expected JLabel in the leaves of my JTree ?
I want to construct a Jtree in which each tree leaf is made of a JLabel (displaying an amount and with a coloured background), followed by a normal String (the label of this amount).
An array (of arrays) of Ojects describes the tree that I want to display in a Swing JPanel of Container, as in the "2.1 Simple JTREE Example" at URL
http://www.apl.jhu.edu/~hall/java/Swing-Tutorial/Swing-Tutorial-JTree.html
So, using the "DefaultMutableTreeNode" class and a "private DefaultMutableTreeNode processHierarchy(Object[] hierarchy)" re-entering function.
Either the 'nodeSpecifier' is of type 'new Object[]', and the 'processHierarchy()' interpretes it as a new node,
Or the 'nodeSpecifier' is of type 'JLabel' (or 'String'), and the 'processHierarchy()' has to interprete it as a new leaf.
Of course, 'JLabel', as 'String', is also a subclass of 'Object'.
        BigDecimal TotalDistrNetBeh1= 1.11;
        Object[] hi�rarchie =
        { "Blablabla",
          new Object[]
          { "Bloc de compteurs",
            new Object[] { "Total1" + " : The 1st listed item = The title of this node",
                                 new JLabel(TotalDistrNetBeh1.toPlainString()),
                   /* + "DistrNetBeh1" */
                                 new JLabel(" 2.22")
                   /* + "DistrNetBeh2" */
            new Object[] { "Total2" + " : Title of this node",
                                 new JLabel("Total Bijdrage Herniewbare energie"),
               /* Test : Leaf of type 'String' mixed with leaves of type 'JLabel'.
                                 "Total Opties : French and Dutch",
                                 "<html>Total Bijdrage <font color=red>WarmteKrachtKoppeling</font></html>",
                                 TotalDistrNetBeh1.toPlainString() + "Test1",
                                 new JLabel("<html>Total <font color=blue>Test2</font></html>")
        };In the displayed tree, rows with JPanel appear like this :
javax.swing.JLabel[,0,0,0x0,invalid,alignmentX=0.0,alignmentY=0.0,border=,flags=8388608,maximumSize=,minimumSize=,preferredSize=,defaultIcon=,disabledIcon=,horizontalAlignment=LEADING,horizontalTextPosition=TRAILING,iconTextGap=4,labelFor=,text= 2.22,verticalAlignment=CENTER,verticalTextPosition=CENTER]
<b>instead of simply " 2.22"</b>, as if there is a hiden (java.lang.String) casting. Why ?
Nevertheless, the 'nodeSpecifier' argument in
        else
          child = new DefaultMutableTreeNode(nodeSpecifier); // Leafis casted to (javax.swing.JLabel)
and 'child' and 'node' - both of 'Object' type - seem to be casted to (javax.swing.tree.DefaultMutableTreeNode)
For memo :
    private DefaultMutableTreeNode constructHi�rarch(Object[] hi�rarchie)
    { DefaultMutableTreeNode node = new DefaultMutableTreeNode(hi�rarchie[0]);
      DefaultMutableTreeNode child;
      for(int i=1; i<hi�rarchie.length; i++)
      { Object nodeSpecifier = hi�rarchie;
if (nodeSpecifier instanceof Object[]) // Node with children
// Re-entering the function
child = constructHi�rarch((Object[])nodeSpecifier);
else
child = new DefaultMutableTreeNode(nodeSpecifier); // Leaf
node.add(child);
return(node);
Is it "DefaultMutableTreeNode(nodeSpecifier)" or "add(child)" that cannot operate properly with a argument of type 'JLabel' ?
How to solve it ?
Sorry, I'm a beginner in Java and Swing.
Thanks in advance.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

Learn to properly use a TreeCellRenderer
You never need to add a Component to a JTree, ie JLabel. You add the data, like a String, and then render the component you want to appear. Already, the String you have in your JTree are being rendered using JLabels, with a White Background. Hence, you need to provide a custom renderer that allows you to display different coloured rows depending on your condition or requirements.
Read a little more on the TreeCellRenderer here: http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html
ICE

Similar Messages

  • Mix string and tags

    Hi all,
    I am using a <bean:message> Struts tag to write an internat. message to the JSP page. In this message I use one argument.
    login.info=Fill in this {0}
    This argument must be a hyperlink. The name of the hyperlink is also an internat. message
    login.regform=registration form
    The hyperlink is:
    <bean:message key="login.regform"/>
    To get this hyperlink in the argument of the first message I would have to do something like this:
    <bean:message key="login.info" arg0='<bean:message key="login.regform"/>'/>
    Using this, I get the following output:
    Fill in this
    When I look at the source code I see this:
    Fill in this <bean:message key="login.regform"/>
    It seems that the tag <bean:message> has not been translated.
    Can somebody tell me the reason? Is there a solution/alternative?
    Thank you very much for your information.

    Yeah, this is a problem. You can't nest taglib tags like that. The simplest way is just to make separate messages in the properties file for whatever you need. If you really need to get a message to include in another message, you have to get the nested one the hard way:
         public String getMessage(String bundle, String key) {
              try {
                   if(bundle == null) {
                        bundle = org.apache.struts.Globals.MESSAGES_KEY;
                   org.apache.struts.util.MessageResources mr = (org.apache.struts.util.MessageResources)getPageContext().getSession().
                        getServletContext().getAttribute(bundle);
                   Locale locale = (Locale)getPageContext().getSession().getAttribute(
                        org.apache.struts.Globals.LOCALE_KEY);
                   return mr.getMessage(locale, key);
              } catch(Exception e) {}
              return "";
         }<bean:message key="login.info" arg0='<%= "<a href=\"......\">"+getMessage(null, "login.regform")+"</a>" %>'/>

  • Saving NSDatePicker to a string and saving that to NSUserDefaults...

    Saving NSDatePicker to a string and saving that to NSUserDefaults I have it saved to a string then I have code that should save it to NSUSerDefaults so that when the program starts it is saved as the string not null. Here is the code [CODE]#import "MainView.h"
    #import "DateView.h"
    @implementation MainView
    -(void)awakeFromNib
    [self removeFromSuperview];
    [self addSubview:dateView];
    [dateView setdateandtime];
    [dateView permsavedattime];
    @end [/CODE] [CODE]#import "DateView.h"
    #include "MainView.h"//Use #import this is to see if #include Works
    @implementation DateView
    -(IBAction)showuserdefaultdate
    [self userdefaultdate];
    //dateoutput.text =tddate;
    -(void)permsavedattime
    tddate=[prefs stringForKey:@"testing"];
    tdtime=[prefs stringForKey:@"timetesting"];
    dateoutput.text =[[NSString alloc] initWithFormat:@"%@",tddate];
    -(void)userdefaultdate
    prefs =[NSUserDefaults standardUserDefaults];
    [prefs setInteger:tddate forKey:@"testing"];
    [prefs setObject:tdtime forKey:@"timetesting"];
    -(void)setdateandtime
    [Today setDate:[NSDate date] animated:YES];
    //formatting date style
    dateformatter = [ [ NSDateFormatter alloc ] init ];
    [ dateformatter setDateStyle:NSDateFormatterLongStyle];
    [ dateformatter setTimeStyle:NSDateFormatterNoStyle ];//makes it so the time is not included
    //[ formatter setTimeStyle:NSDateFormatterLongStyle ];//set to anystyle besides
    //NoStyle if you dont want time included.
    [Time setDate:[NSDate date] animated:YES];
    //formatting date style
    timeformatter = [ [ NSDateFormatter alloc ] init ];
    [ timeformatter setDateStyle:NSDateFormatterNoStyle];//makes it so it doesn't get the date
    [ timeformatter setTimeStyle:NSDateFormatterShortStyle];//makes it so the time is just hour and minute and A.M. or P.M.
    //[ formatter setTimeStyle:NSDateFormatterLongStyle ];//set to anystyle besides
    //NoStyle if you dont want time included.
    -(IBAction)recieveDate
    tddate= [dateformatter stringFromDate:Today.date];//Asigning the date to the string
    dateoutput.text =tddate;
    -(IBAction)recievetime
    tdtime= [timeformatter stringFromDate:Time.date];//Asigning the date to the string
    timeoutput.text =tdtime;
    -(IBAction)canceltime
    [Time setDate:[NSDate date] animated:YES];
    tdtime= [timeformatter stringFromDate:Time.date];//Asigning the date to the string
    timeoutput.text =tdtime;
    -(IBAction)canceldate
    [Today setDate:[NSDate date] animated:YES];
    tddate= [dateformatter stringFromDate:Today.date];//Asigning the date to the string
    dateoutput.text =tddate;
    @end[/CODE] What am I missing? It keeps coming up Null I need it saved right so I can send it through email

    softwarespecial wrote:
    why can't I have the prefs saved in the .h
    You can save that address in an ivar if you want to, but there's no purpose to that. The standardUserDefaults object is a +shared class object+. It's like a dictionary object that's maintained for your program by the NSUserPreferences class. You can read from or write to it at any time for the duration of your program. So whenever you get the shared object's address [NSUserDefaults standardUserDefaults], you're just getting the address of that same object each time.
    In case the above doesn't make sense, I ran across a good explanation by Danneman in the last message on this page: [http://www.iphonedevsdk.com/forum/iphone-sdk-development/18716-set-settings-va riable-code.html].
    When I did that as you so wisely pointed out it didn't work but when I saved it at each point I needed it it works.
    When you change two things at once it's easy to forget the first and assume the second change solved the problem. Actually, I don't think saving prefs in your ivar had anything to do with your bug. What fixed it was getting a pointer to the shared std defaults object in this method:
    -(void)permsavedattime
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults]; <-- get the shared object
    tddate=[prefs stringForKey:@"testing"];
    tdtime=[prefs stringForKey:@"timetesting"];
    dateoutput.text =[[NSString alloc] initWithFormat:@"%@",tddate];
    Without the first line of the above, I'm fairly sure that your prefs ivar was nil. I didn't see any code that initialized that ivar prior to the first time userdefaultdate ran. It looked to me like permsavedattime ran at start up, well before prefs was set in userdefaultdate. If you're interested in backtracking, restore the file to the way it was when you posted, then add a NSLog() like this:
    -(void)permsavedattime
    // NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults]; <-- get the shared object
    NSLog(@"prefs=%@", prefs);
    tddate=[prefs stringForKey:@"testing"];
    tdtime=[prefs stringForKey:@"timetesting"];
    dateoutput.text =[[NSString alloc] initWithFormat:@"%@",tddate];
    I wish to save lets say five different things to NSUSerDefaults would I be able to do it all with my NSUserDefaults prefs or would I have to create a another one for some of them?
    You know the answer to your second question now, right? The important point is that you're never creating the shared object, you're just asking for its address whenever you need it.
    Btw, there's another user defaults method you should know about: The synchronize method writes the data to disk. You might want to do that when your app is ready to exit. E.g., in the app delegate:
    - (void)applicationWillTerminate:(UIApplication *)application {
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    [prefs synchronize];
    Although the docs suggest synchronize when the app is about to exit, I'm not sure it's necessary. I think the system might write the defaults out to disk anyway when the app terminates, but not sure about this. +User Defaults Programming Topics for Cocoa+ says:
    On Mac OS X v10.5 and later, in applications in which a run-loop is present, synchronize is automatically invoked at periodic intervals. Consequently, you might synchronize before exiting a process, but otherwise you shouldn’t need to.
    The above is in the iPhone edition, so I think it applies.
    It might also be a good idea to update the data and call resetStandardUserDefaults in didReceiveMemoryWarning. I'm not clear about the need for reset either though, since the system may do that for you as well. But on a memory warning, you would definitely want to update the user default data if some of it is stored in an object to be released. You can find out how your app behaves on a memory warning by selecting Hardware->Simulate Memory Warning from the iPhone Simulator menu.
    - Ray

  • What is difference between Null String and Empty String ?

    Hi
    Just i have little confusion that the difference bet'n NULL String and Empty String ..
    Please clear my doubte.
    Thankx

    For the same reason I think it's okay to say "null
    String" and "empty String "as long as you know they
    really mean "null String reference" and "empty String
    object" respectively. Crap. It's only okay to say that as long as *the one you're talking to" knows what it really means. Whether you know it or not is absolutely irrelevant. And there is hardly any ambiguity about the effects that a statement like "assign an object to a reference" brings. "Null String" differs in that way.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Adding a jar to the classpath of an executable jar (mixing -jar and -cp)

    Hello,
    frankly I hesitated over posting this to "New to Java"; my apologies (but also, eternal gratefulness) if there is an ultra-simple answer I have overlooked...
    I integrate a black-box app (I'm not supposed to have the source) that comes packaged as an executable jar (with a Manifest.MF that specifies the main class and a bunch of dependent jars), along with a few dependent jars and a startup script. Long story short, the application code supports adding jars in the classpath, but I can't find a painless way to add a jar in its "classpath".
    The app's "vendor" (another department of my customer company) has a slow turnaround on support requests, so while waiting for their suggestion as to how exactly to integrate custom jars, I'm trying to find a solution at the pure Java level.
    The startup script features a "just run the jar" launch line:
    java -jar startup.jarI tried tweaking this line to add a custom jar in the classpath
    java -cp mycustomclasses.jar -jar startup.jarBut that didn't seem to work ( NoClassDefFound at the point where the extension class is supposed to be loaded).
    I tried various combination of order, -cp/-classpath, using the CLASSPATH environment variable,... and eventually gave up and devised a manual launch line, which obviously worked:
    java -cp startup.jar;dependency1.jar;dependency2.jar;mycustomclasses.jar fully.qualified.name.of.StartupClassI resent this approach though, which not only makes me have to know the main class of the app, but also forces me to specify all the dependencies explicitly (the whole content of the Manifest's class-path entry).
    I'm surprised there isn't another approach: really, can't I mix -jar and -cp options?
    - [url http://download.oracle.com/javase/6/docs/technotes/tools/windows/classpath.html]This document (apparently a bible on the CLASSPATH), pointed out by a repited forum member recently, does not document the -jar option.
    - the [url http://download.oracle.com/javase/tutorial/deployment/jar/run.html]Java tutorial describes how to use the -jar option, but does not mention how it could play along with -cp
    Thanks in advance, and best regards,
    J.
    Edited by: jduprez on Dec 7, 2010 11:35 PM
    Ahem, the "Java application launcher" page bundled with the JDK doc (http://download.oracle.com/javase/6/docs/technotes/tools/windows/java.html) specifies that +When you use [the -jar] option, the JAR file is the source of all user classes, and other user class path settings are ignored+
    So this behavior is deliberate indeed... my chances diminish to find a way around other than specifying the full classpath and main class...

    I would have thought that the main-class attribute of the JAR you name in the -jar option is the one that is executed.Then I still have the burden of copying that from the initial startup.jar's manifest. Slightly less annoying than copying the whole Class-path entry, but it's an impediment to integrating it as a "black-box".
    The 'cascading' behavior is implicit in the specification
    I know at least one regular in addition to me that would issue some irony about putting those terms together :o)
    Anyway, thank you for confirming the original issue, and merci beaucoup for your handy "wrapper" trick.
    I'll revisit the post markers once I've actually tried it.
    Best regards,
    Jérôme

  • Word 2007 mail merge : problem with mixed portrait and landscape orientations

    Hi there,
    I have a 3 pages document Word 2007 file
    This is a mail merge I want to export in PDF using Adobe Acrobat Printer,
    then send "big" PDF to printing.
    page 1 is PORTRAIT
    page 2 is PORTRAIT
    page 3 is LANDSCAPE
    In PDF pages 1 and 2 are perfectly fine, inside an A4 format (width=210 height=297mm or something)
    but for page 3, system changed to a "double" sized page (A3 width=297 height=420) and printed my stuff at the 1st top middle of big page.
    So I have a big "double" sheet, oriented PORTRAIT, with my stuff in 1st half, and a blank in 2nd half.
    It seems that system did not rotate the page... and just put the stuff into a bigger sheet to "solve" at best.
    I would like the same size of paper (A4) but in landscape : width=297 height=210
    I have already seen many PDF with mixed portrait and landscape orientations, so what's the thing ?
    With my advanced thanks,
    And greetings from Paris, France !
    Vince

    Some questions:
    Which version of office were you using before? 2003?
    Are the data files on a network, or on your local machine? If they are on a network, can you make a copy of one of them on your local machine and try again?
    Can you open the files directly in Excel? What extension do they have (.xls, or something else?) I am wondering whether access to other file types has been left blocked on your machine but is allowed on your colleague's machine.
    Are you just opening the mail merge main document and seeing this message? If so, do you see the same thing if you start with a new document and try to connect to one of these data sources?
    Can you confirm that the message is about Access even though you are trying to connect to an Excel file?
    (Also, office 2007 has some new stuff - that let's you specify that certain folders are "trusted" . I don't think that ever affected MailMerge but it may be as well to make sure that your documents and data sources are in trusted locations).
    Also worth trying to start Word in "Safe mode" - see, e.g. http://office.microsoft.com/en-gb/word-help/work-with-office-safe-modes-HP010140792.aspx
    Peter Jamieson

  • How to read a data file combining strings and data

    Hello,
    I'm having a data file combining strings and datas to read. I'm trying to read the filename, time, constants and comments into four seperate string indicators (the lines for the comments varies for different files). And read the data into a 2-D numeric array. How can I do this? Is there any function that can serch special characters in the spreadsheet file so I can exactly locate where I should start reading the specific data. The following is how the data file appears. Thank you very much.
    Best,
    Richard
    filename.dat
    14:59:00 12/31/2009
    Sample = 2451
    Frequency = 300, Wait time = 2500
    Temperature = 20
    some comments
    some comments
    some comments
    some comments
    some comments
    7.0000E+2    1.5810E-5
    7.0050E+2    1.5400E-5
    7.0100E+2    1.5500E-5
    7.0150E+2    1.5180E-5
    Message Edited by Richard1017 on 10-02-2009 03:10 PM
    Solved!
    Go to Solution.

    Hi,
         I'm fairly new to the NI forums too and I think you just have to wait longer.  Your post was done right.  I do a similiar function as to what you are talking about except I read in numbers from a file.  I create an ini file (just a notepad file of type *.ini) that is is set up with sections inside brackets [] and keys with whatever name followed by an = sign.  You may be able to use a *.dat file too, I just haven't.  Then the vi attached goes to that file and reads the keys from those sections.  You just repeat for the different sections and keys you want to read.  You can use similar provide VI's to write to that same file or create it.  Let me know how that works. 
    Attachments:
    Help1.ini ‏1 KB
    Help1.vi ‏10 KB

  • Compare a string and a binary value

    Hi!
    I would like to compare two passwords encoded into two different's LDAP directory.
    For these two directories, I have not the same libraries, so that the encoded value of the first password returned is a String, and the second one is a binary.
    Could you tell me if it is possible to compare them?
    Thanks a lot!
    Best regards

    Hi dwg,
    in LDAP directories, there is no encryption. There is
    hash coding.
    The same method of hashcoding is used in the two
    directories, but we do not have (and we cannot)
    decode the data.
    We only have to compare the two hashcoded values.
    About the "binary", you are right. It is a byte
    array.
    How about this function:
    equals (<string parameter>, new String(<array
    parameter>, "UTF8"))
    do you think it is OK?
    Thanks for your help!So you have a hashcode from one directory, and a plaintext String from the other? In that case you have to hash the plain String and then compare the two hashes. You can't turn a hash back into a String, which you seemed to point out when you said "but we do not have (and we cannot) decode the data."

  • Https site with no mixed content and EV cert is shown as mixed and not identifiying itself

    My site https:orderform page contains only https images and website has an EV cert that is valid and current. With history cleared and visiting page for first time Firefox reports that page contains mixed content and that site does not identify iteself.
    Hitting F5 to refresh the page address bar correctly shows green with no mixed content popup and that side idenfies itself.
    SSLCertificateChainFile has been added and this makes no difference.
    Problem does not occur in other browsers (IE, Safari, Chrome).
    A new FF profile has been tried but same problem occurs.
    Why would refeshing the page work?
    Problem affects all firefox browsers 3.5 to 14.01. I dont know about those <3.5.
    I have read and tried most suggestions in forum and elsewhere but cant find a solution.
    I have not provided the url as this is my order page and its important for me to see genuine visitors.

    First a reply to Jsher2000
    Thank you for your suggestions. Yes and Yes did this ages ago but no non-https content.
    I have found a workaround for what appears to be a bug in Firefox:-(
    Here is the non-perfect workaround. First Detect firefox
    xUA=navigator.userAgent.toLowerCase()
    xFf=xUA.indexOf('firefox')!=-1
    if(xFf) top.location.href='https://ord.html'
    else top.location.replace( 'https://ord.html' )
    The current non-secure page is being replaced with a secure one.
    Internet Quote:
    "The difference between location.href and location.replace is that the former creates a new history entry on the visitor's browser meaning that if they hit the back button, they can get in a 'redirection loop' which is usually undesirable and may have unwanted side effects."
    It appears that FF is using some content (cached) from the previous non-secure page when replacing - leading to the mixed content and non-identified site. An F5 refresh or reload of current page will show that site identifies iteself and there is no mixed content.
    In summary its a Firefox Bug.

  • What Are the Differences Between String and StringBuffer?

    Both String and StringBuffer are final classes. StringBuffer grows in size dynamically. Could people help to detail other differences between String and StringBuffer?

    String is immutable. In other words, once it is made, the contents of that instance of String cannot be changed (easily). The size and characters cannot be changed, and code can take advantage of this fact to optimize space. Also, once you have a reference to a string, you do not need to worry about it changing at all, so you can eliminate constant tests to verify things such as size in another class that may want to hold onto the string.
    StringBuffer, as you noticed, can change dynamically. While this provides flexibility, it cannot be optimized and assumptions cannot be made as with strings. If a class holds a reference to a StringBuffer that it does not own, there is a possibility that it may change things such as size when the class tries to use it later. StringBuffer is also less efficient in handling space then an equivalent String. The character array to hold a String is exactly the length to hold all the characters. StringBuffer, on the other hand, adds a 16 character buffer of array space for possible expansions. Also, the size of the internal array doubles when its internal capacity is exceeded. So, unless you explicitly maintain the size, a StringBuffer will take up more memory then an equivalent String, and if your program needs thousands of instances of Strings (which is not uncommon), that space can add up.
    I hope this helps clarify some things for you.
    -JBoeing

  • Returning strings to JLabel

    I'm making a program which included returning abstract string from the other class to the label. It works good, but the only problem is that the string is always displayed in one line in the label. I use the correct command to make a multiline string and it works perfectly when I implement the string alone in a test program, but when I return it to the label it again displays in single line. Any advices on this one ?

    A JLabel always displays as a single line of text (unless you use HTML),
    If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html], that demonstrates the incorrect behaviour.
    Don't forget to use the Code Formatting Tags so the posted code retains its original formatting. That is done by selecting the code and then clicking on the "Code" button above the question input area.

  • Possible to mix SAS and SATA in S10?

    The S10 I purchased has the 146GB SAS drive attached to the LSI controller.  I see in the hardware reference manual that there are spare SATA ports on the main board.  Can I mix SAS and SATA drives on this machine if I am *not* using them in a RAID array?  Does the fact that the SAS and SATA are likely to have different rotational speeds mean that I need to be worried about vibration/stability issues?
    Solved!
    Go to Solution.

    SAS and SATA can definitely coexist.   rotational speeds won't matter as the drives are harmonically dampened in their trays.   in fact, i have three 15,000 RPM SAS drives sandwiching two 7200 RPM SAS drives in my D10 and can't feel any vibration in any of them.   i've also hot-plugged SATA hard drives onto the intel controller with no issues.
    ThinkStation C20
    ThinkPad X1C · X220 · X60T · s30 · 600

  • Confusion building JTree from path strings

    If I have a bunch of strings like this:
    "/dira/dir1/file1"
    "/dira/dir1/file2"
    "/dira/dir2/file1"
    "/dira/dir3/anotherdir/file1"
    etc.
    Does anybody have an easy solution to getting them in a JTree that looks like this:
       dira
        |
        +-dir1
        |  |
        |  +-file1
        |  |
        |  +-file2
        |
        +-dir2
        |  |
        |  +-file1
        |
        +-dir3
           |
           +-anotherdir
              |
              +-file1Mainly I am having trouble getting the tree to populate without duplicating nodes. For example dir1 gets listed twice. I am looking for a solution that will parse these strings and build the tree. I have found demos that read a file system, but nothing that works with strings. I have tried to pick apart the file system demos, but so far I can't get it to work correctly.
    Thanks,
    Jeff

    This compiles and works (with 1.4):
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import java.util.HashMap;
    public class TreeStrings extends JFrame {
        public TreeStrings() {
            super("Tree strings");
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            setSize(500, 400);
            String[] inputStrings = {"/dira/dir1/file1", "/dira/dir2/file1", "/dira/dir2/file2"}; // your bunch of Strings     
         DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("www");
         HashMap nodeMap = new HashMap();
         for(int i = 0; i < inputStrings.length; i++) {
             String s = inputStrings;
         DefaultMutableTreeNode lastNode = rootNode;
         int lastIndex = 0;
         while(true) {
              DefaultMutableTreeNode tempNode = null;
              int nextIndex = s.indexOf("/", lastIndex + 1); // <- i forgot + 1
              if(nextIndex != -1) { //we are somewhere in middle of s, checking nodes from root to leaf, one by one.
         String nodeKey = s.substring(0, nextIndex);
         if(nodeMap.get(nodeKey) == null) { //no such node, must make one
              String nodeName = s.substring(lastIndex, nextIndex); // you want the last nodeKey word for node name
         DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(nodeName);
         nodeMap.put(nodeKey, newNode);
         lastNode.add(newNode);
         lastNode = newNode;
         else { //allready such node, just put it to be lastNode
         lastNode = (DefaultMutableTreeNode) nodeMap.get(nodeKey);
    lastIndex = nextIndex;
         else { //no more "/" , it means we are at end of s, and that all parent nodes for this leaf-node exist.
         // and we just add the leaf node to last node
         String leafName = s.substring(lastIndex, s.length());
         DefaultMutableTreeNode leafNode = new DefaultMutableTreeNode(leafName);
         lastNode.add(leafNode);
         break; // go to next s
         //You first make your tree structure with DefaultMutableNodes,
         //Then make a DefaultTreeModel with the root node,
         //Then make a Tree with the DefaultTreeModel
         DefaultTreeModel treeModel = new DefaultTreeModel(rootNode);
    JTree yourTree = new JTree(treeModel);
    getContentPane().add(yourTree, BorderLayout.CENTER);
    show();
    public static void main(String[] args) {
         new TreeStrings();
    Anything else?

  • Having some problems with ImageIcons and JLabels

    I'm making a checkers game, and so far it's going pretty well.
    I've got the basic game down, and you can move pieces, jump, your turn ends when you can't jump anymore, etc...
    However, I've had three problems:
    1.) I'm using JLabels to display my board (8 x 8.. well actually 9 x 9 for an outer row labelled A,B,C,D.. 1,2,3,4...) Anyway, I create the JLabels using something that looks like \:
    JLabel square = new JLabel(new ImageIcon("pic.png"));
    Now, the picture loads properly, but it seems like the picture is being cropped, and the top and bottom are getting chopped off, so my 36 x 36 pixel *.gif appears to be 36 x 30.
    You can see how there is a gap created in:
    http://img235.imageshack.us/img235/7765/prob13ky.jpg
    Now the problem may be with the GridLayout I am using, but I set the distance between the components in the container to be 0, 0 so I don't think that GridLayout is chopping my icons. I've also tried setPreferredSize(new Dimension(36,36))
    for both my ImageIcons and JLabels and for my container (which I set to size 2000,2000, just to make sure there was room). If anyone can help me, it's be appreciated.
    2.) I used to be able to view my outside row/column of squares that said A,B,C,D.... and 1,2,3,4... with the square in the corner having a random pic. For some reason now (have no clue why) I now see only the pic in the corner, and then a little gray smudge diagonally under it.
    Pic:
    http://img347.imageshack.us/img347/8308/prob24im.jpg
    I don't know what's wrong. I'm pretty sure it's none of the new methods I've written, as those are all in my static void main (String[] ar) ...... and if I comment all the methods in my main except where I first make the JFrame and set it visible, it still turns out like that. repaint() doesn't help.
    3.) For some reason, when I move another window (AIM, the console window, etc...) over my Swing window, it "erases" (turns gray, just wipes clean) the part where I have my squares that have pieces.
    What's weird is that:
    The border pieces (err.. my one visible corner piece from my second problem) don't get wiped, and some debugging text and JLabels (in a different JPanel) are fine. I don't think the JPanel matters though; the border pieces and the playing squares (which get wiped) are in the same JPanel and same array of squares.
    repaint(); also erases ALL of my playing squares, whereas moving a window over them would only erase the part that the window covered.
    Also, I added a mouseListener so that whenever I move the mouse over a square, it changes the image (to a tinted version, so you know the mouse is over it) and when you move the mouse away, it returns to normal. However, if I wildly swing the mouse around the area, it seems to lock up and freeze for a few seconds. Is there anything I can do to prevent this??
    Thanks in advance.

    It is hard to tell what your problems are without any code at all (I saw your images, but that doesn't make it easy to see what is wrong in your code). If you do post code, please use code tags (see button above posting box).
    I've seen your MouseListener problem before--we had the exact same issue in our code at work. It would freeze up while it processed all of the mouse events (unbearably slow). I'm not at work right now, so I don't recall how it was fixed. Essentially, you need to only process the event periodically. You need to only update the image if the mouse switches squares. Or, only update the image if the distance from the last mouse event is more than some specified amount. We might also have checked the time difference between mouse events before processing a new one. I could look at the code at work tomorrow, if you are still having trouble.

  • Search for string and move decimal

    Hello,
    I am trying to write code that will search for a fractional string within an array and convert it from mV to V so it can be properly compared to the other fractional string numbers in the array.
    I have an array that outputs x iterations  each with a minimum and maximum column including several different types of decimal strings (negative/positive with several decimal places) each ending with either mV and V (example string: -725.543mV).
    I then split the array into columns containing the minumum and maximum values of each iteration. I want to compare the minimum values of each iteration and find the most minimum, and do the same thing with the maximum values.
    Unfortunatley the way I'm doing it, when I convert from fractional string to number it removes the V or mV unit label but does not convert the number from mV to V. so it compares -725.543mV with -52.334V as -725.543 & -52.334 thus declaring the mV value the most minimum. I need the program to recognize that mV is less than V or search each array for values labeled with mV and move the decimal place so it is in standard V format.
    The unit label is actually part of the string and not the display (as you can see in the code I've attached) and I understand this is a little tricky with the way I have to do it. But this is a dumbed down chunk of code I will eventually incorporate into my larger program which reads the values and their units from several different types of oscilloscopes. The Scopes output the values as strings as they appear on the screen and don't differentiate between mV and V unless they are told to output the units which just tags them on the end of the string.
    I'm sorry for the large post. SO to sum up I need to search an array to make sure all values have the same units, if they don't I need to convert each value to the proper unit and output the max and min from the resulting array. my code is attached. Thank you for your help.
    Solved!
    Go to Solution.
    Attachments:
    File manipulation.vi ‏15 KB

    crossrulz wrote:
    jcarmody wrote:
    camerond wrote:
    Sorry, Jim, that's not quite right. You forgot to consider significant figures (your third min is not quite right). [...]
    Good catch, but, really?   
    That "Finally!" comes out to -5569492V to me.  Holy crap.  -5.569492MV!  I think there's a problem there.
    Carp! Stupid negative numbers, shouldn't be allowed. Put a piece of duck tape over the place for that negative sign, that'll fix it.
    I'll get back, it's now a matter of principle.
    Jim, how does your algorithm do when there are 8 or 9 sig figs, say -56.9492345mV? (Yep, too lazy to draw it in myself.)
    Cameron
    To err is human, but to really foul it up requires a computer.
    The optimist believes we are in the best of all possible worlds - the pessimist fears this is true.
    Profanity is the one language all programmers know best.
    An expert is someone who has made all the possible mistakes.
    To learn something about LabVIEW at no extra cost, work the online LabVIEW tutorial(s):
    LabVIEW Unit 1 - Getting Started
    Learn to Use LabVIEW with MyDAQ

Maybe you are looking for