How can I create an alt background color for items in a jlistbox or jtree

What I'm looking to do is have a white background for say items 1,3,5, etc. and a light yellow background for items 2,4,6, etc. I was wondering how can I set an alternative background color on items in a JTree or a JList

Use a cell renderer:
import java.awt.*;
import javax.swing.*;
public class ListAlternating extends JFrame
     public ListAlternating()
          String[] items = {"one", "two", "three", "four", "five", "six", "seven"};
          JList list = new JList( items );
          list.setVisibleRowCount(5);
          list.setCellRenderer( new MyCellRenderer() );
          JScrollPane scrollPane = new JScrollPane( list );
          getContentPane().add( scrollPane );
     public static void main(String[] args)
          ListAlternating frame = new ListAlternating();
          frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
          frame.pack();
          frame.setLocationRelativeTo( null );
          frame.setVisible( true );
     class MyCellRenderer extends DefaultListCellRenderer
          public Component getListCellRendererComponent(
               JList list, Object value, int index, boolean isSelected, boolean cellHasFocus)
               super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
               if (!isSelected)
                    setBackground(index % 2 == 0 ? list.getBackground() : Color.LIGHT_GRAY);
               return this;
}

Similar Messages

  • How can I create a single background image for a BorderLayout?

    I can create a background with an image file for the individual panel (North, West, Center, East and South) in a BorderLayout, but I've been spinning my wheel for a long while now trying to figure out how to create just one background with a single image file for all of these panels?
    In my application, a panel may contain various buttons, a listbox, a group of checkboxes, a combo box, or a canvas. Even if I used the same image file, when the panels are finally put together, one can clearly see that the end product is the result of a lot of patch works.
    Hope someone has an answer for this. BTW, I'm using AWT because it works with existing browsers without the need for a separate Java plug-in.
    Regards,
    V.V.

    Look at this :
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.awt.image.BufferedImage;
    public class PanI extends Frame
         Image map;
         Panel pan;
         myPan p8,p4,p6,p2,p5;
         BufferedImage I;
    public PanI() 
         addWindowListener(new WindowAdapter()
        {     public void windowClosing(WindowEvent ev)
              {     dispose();
                   System.exit(0);}});
         map = getToolkit().getImage("map2.gif");
         MediaTracker tracker = new MediaTracker(this);
         tracker.addImage(map,0);
         try   {tracker.waitForID(0);}
         catch (InterruptedException e){}
         I = new BufferedImage(1,1,BufferedImage.TYPE_INT_ARGB);
         setBounds(10,10,map.getWidth(null)+8,map.getHeight(null)+27);
         setLayout(new BorderLayout());
         pan = new Panel();
         add(pan,BorderLayout.CENTER);
         pan.setLayout(new BorderLayout());
         pan.setSize(map.getWidth(null),map.getHeight(null));
         p5 = new myPan(5);
         p5.setBackground(Color.red);
         pan.add(p5,BorderLayout.CENTER);
         p8 = new myPan(8);
         p8.setBackground(Color.orange);
         pan.add(p8,BorderLayout.NORTH);
         p4 = new myPan(4);
         p4.setBackground(Color.blue);
         pan.add(p4,BorderLayout.WEST);
         p6 = new myPan(6);
         p6.setBackground(Color.green);
         pan.add(p6,BorderLayout.EAST);
         p2 = new myPan(2);
         p2.setBackground(Color.pink);
         pan.add(p2,BorderLayout.SOUTH);
         setVisible(true);
    public class myPan extends Panel
         int where;
    public myPan(int i)
         super();
         where = i;
    public void paint(Graphics g)
         if (I.getWidth(null) != pan.getWidth() || I.getHeight(null) != pan.getHeight())
              I = new BufferedImage(pan.getWidth(),pan.getHeight(),BufferedImage.TYPE_INT_ARGB);
              Graphics      G = I.getGraphics();
              G.drawImage(map,0,0,pan.getWidth(),pan.getHeight(),null);     
              G.dispose();
         int x1=0;
         int x2=getWidth();
         int y1=0;
         int y2=getHeight();
         if (where == 8)
         if (where == 2)
              y1 =  p8.getHeight()+p5.getHeight();
              y2 =  getHeight()+y1;
         if (where == 4)
              y1 =  p8.getHeight();
              y2 =  y1+getHeight();
         if (where == 5)
              x1 =  p4.getWidth();
              x2 =  x1+getWidth();
              y1 =  p8.getHeight();
              y2 =  y1+getHeight();
         if (where == 6)
              x1 =  p4.getWidth()+p5.getWidth();;
              x2 =  x1+getWidth();
              y1 =  p8.getHeight();
              y2 =  y1+getHeight();
         g.drawImage(I,0,0,getWidth(),getHeight(),x1,y1,x2,y2,null);
    public void update(Graphics g)
         paint(g);
    public static void main (String[] args) 
         new PanI();
    Noah

  • How can I create a new ring tone for my iPhone 4?

    How can I create a new ring tone for my iPhone 4? I followed the Garage Band process and ended up with the ring tone I want as a AAC audio file. It got stored in my iTunes a a song rather than a ring tone. How do I make it a ring tone vs. a song? I tried dragging it t the Ring Tone category at the bottom of the ITunes list, but it won't alloow me to move it?

    There's also an easy to use Applescript over at Doug's Applescripts for iTunes. It automates the whole thing. All you do is set the start and stop time on a file in iTuens and run the script. It will do everything else.
    Make Ringable v1.1
    http://dougscripts.com/475

  • How can I create a sub-iTunes account for a teen?

    how can I create a sub-iTunes account for a teen?
    I need to separate our music libraries but still keep it under control from the main account (mine).

    iOS 5 & iCloud Tips: Sharing an Apple ID With Your Family

  • How can I create a magazine web app for all devices?

    How can I create a magazine web app for all devices?

    magazine web app is not supported in DPS as of now. You can share the contents to preview it on web content viewer.

  • How can i create a bootable usb sata for xp

    how can i create a bootable usb sata for xp

    Installing Windows XP on a portable USB hard drive is not supported.
    Carey Frisch

  • How can I create a start up disk for a old intel core duo running 10.5.8.. Computer works fine, but can't find install disk.

    How can I create a start up disk for a old intel core duo running 10.5.8.. Computer works fine, but can't find install disk. Want to use internal disk drive or USD flash drive.

    Try calling 1-800-676-2775.  Give the serial number and thy *may* still burn you new install disks designed just for the hrdware in your system (for a fee, something like $160 per disk).  *May* is only because they may not burn disks for Leopard anymore.
    If they do not burn them for you, you can buy Leopard disks off Amazon or eBay for about $200.
    Have you considered Snow Leopard?.  Those disks only cost $19 (single user) or $29 (5-user license) through Apple by calling 1-800-MY-APPLE.

  • I have an iCloud email address on my iMac. How can I create an icloud email address for my wife on the same computer?

    I have an iCloud email address on my iMac. How can I create an icloud email address for my wife on the same computer?

    If all you want is an additional email address you can create up to three 'email aliases'  - these are additional addresses (not accounts) which deliver into the same inbox as the main account.
    You should be aware before you start that once you've created an alias you cannot turn that address into a full iCloud account, move it to another account, or reactivate it if you delete it.
    More information on aliases here:
    http://help.apple.com/icloud/#mm6b1a490a
    If you want to keep her email separate from yours she will need to create a new Apple ID, and use it to create a new iCloud account either on a separate computer or on a separate User Account on your Mac.

  • How can i create the blue "I"-Button for the Documentation in a view

    How can i create the blue "I"-Button for the documentation in a view?
    I want to prepare the button with user specified Information...
    and where must be create the documentation?
    thanks
    Edited by: DDC-TD on Apr 24, 2008 10:22 PM

    you have not mentioned where do u want the " I " information button ,
    1. If u want for a report , u can get the information button on selection-screen only .
       if u goto se38 on the mail screen u will find a radio button for documentaion ,
    when u select it and click 'create' or 'change' , an editor will open and u can document anything there ....
    2. Or specify where u want  info button .
    thanks ,
    reward points if usefull.

  • How can i create datasource on apache server for ADF application?

    Hi All,
    i my use case i have created simple adf application using ADF BC and want to deploy on Apache server 6.x.
    So my question is that  how can i create Data Source i have goggling and find  two different way to do this.
    1. write following line of code on apache server conf/Context.xml file.
    <Resource name="jdbc/TestDB" auth="Container"
                  type="javax.sql.DataSource"
                   driverClassName="oracle.jdbc.OracleDriver"
                  url="jdbc:oracle:thin:@localhost:dst"
                  username="jagrandb" password="jagrantest" maxActive="20" maxIdle="10"
                  maxWait="-1"/>
    but when i have used this way i got following exception.
    org.apache.tomcat.dbcp.dbcp.PoolingDataSource$PoolGuardConnectionWrapper cannot be cast to oracle.jdbc.OracleConnection
    check link-
    https://forums.oracle.com/thread/2564233
    2. write following line of code apache conf/Server.xml file
    <GlobalNamingResources>
        <!-- Editable user database that can also be used by
             UserDatabaseRealm to authenticate users
        -->
        <Resource name="UserDatabase" auth="Container"
                  type="org.apache.catalina.UserDatabase"
                  description="User database that can be updated and saved"
                  factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
                  pathname="conf/tomcat-users.xml" />
    <Resource name="jdbc/TestDB" auth="Container"
                  type="oracle.jdbc.pool.OracleDataSource"
                  description="User database that can be updated and saved"
                  driverClassName="oracle.jdbc.driver.OracleDriver"
                  factory="oracle.jdbc.pool.OracleDataSourceFactory"
                  url="jdbc:oracle:thin:@//172.31.43.207:1521:dst"
                  username="jagrandb" password="jagrantest" maxActive="20" maxIdle="10"
                  maxWait="-1"   />
      </GlobalNamingResources>
    and add this line in context.xml file inside <context> tag
    <ResourceLink global="jdbc/TestDB" name="jdbc/TestDB" type="oracle.jdbc.pool.OracleDataSource"/>
    but when i have run application i have got following error
    log-
    javax.servlet.jsp.JspException: Unable to get connection, DataSource invalid: "java.sql.SQLException: invalid arguments in call"
      at org.apache.taglibs.standard.tag.common.sql.QueryTagSupport.getConnection(QueryTagSupport.java:298)
      at org.apache.taglibs.standard.tag.common.sql.QueryTagSupport.doStartTag(QueryTagSupport.java:181)
      at org.apache.jsp.test_jsp._jspx_meth_sql_005fquery_005f0(test_jsp.java:110)
      at org.apache.jsp.test_jsp._jspService(test_jsp.java:63)
      at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
      at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:374)
      at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:342)
      at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:267)
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
      at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
      at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
      at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
      at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
      at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
      at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:286)
      at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:857)
      at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:565)
      at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1509)
      at java.lang.Thread.run(Thread.java:662)
    Aug 2, 2013 5:17:21 PM org.apache.catalina.core.StandardWrapperValve invoke
    SEVERE: Servlet.service() for servlet jsp threw exception
    javax.servlet.jsp.JspException: Unable to get connection, DataSource invalid: "java.sql.SQLException: invalid arguments in call"
      at org.apache.taglibs.standard.tag.common.sql.QueryTagSupport.getConnection(QueryTagSupport.java:298)
      at org.apache.taglibs.standard.tag.common.sql.QueryTagSupport.doStartTag(QueryTagSupport.java:181)
      at org.apache.jsp.test_jsp._jspx_meth_sql_005fquery_005f0(test_jsp.java:110)
      at org.apache.jsp.test_jsp._jspService(test_jsp.java:63)
      at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
      at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:374)
      at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:342)
      at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:267)
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
      at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
      at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
      at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
      at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
      at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
      at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:286)
      at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:857)
      at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:565)
      at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1509)
      at java.lang.Thread.run(Thread.java:662)
    so what is the solution how to create datasource on apche server which suitable for adf application?
    when i test data source using  following code used 1. way as i mentioned above  its running fine bt not for second.
    <%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    <sql:query var="rs" dataSource="jdbc/TestDB">
    select empname from pay_emphdr where empcd='JK1306'
    </sql:query>
    <html>
      <head>
        <title>DB Test</title>
      </head>
      <body>
      <h2>Results</h2>
    <c:forEach var="row" items="${rs.rows}">
        Foo ${row.empname}<br/>
    </c:forEach>
      </body>
    </html>
    please help me. it is very urgent.
    thanks in Advance
    Manish

    Hi Lindalnci
    i have already tried  this tutorial and in my post i have defined first way to do using this procedure.
    in that case i have got following exception as i have mentioned above
    org.apache.tomcat.dbcp.dbcp.PoolingDataSource$PoolGuardConnectionWrapper cannot be cast to oracle.jdbc.OracleConnection

  • How can I create a folder in ios for pdf files?

    How can I create a separate folder in ios for my pdf files?

    Hi Artistdeet,
    For this you have to follow certain steps-
    1. Tap on Document tab from left pane of Adobe Reader.
    2. Tap on 'Edit' button placed at right side of top toolbar.
    3. Tap on "folder icon with plus sign", it will ask you to enter the folder name.Enter desired folder name by which you want to create the folder.
    Hope this will solve your problem.
    Thanks
    -Satyadev

  • How can I create a Tree with Color Picker icons?

    I'm a newbie to Flex. I want to create a tree which has color
    picker icons.
    As an analogy for the Mac users out there, I envision a
    control like the Calendars section in iCal, where you can specify
    the color for each individual node. These colors are then used in
    other parts of the application.
    The Flex 3 documentation specifies four methods for setting
    node icons on a Tree control, none of which seems to suit my needs:
    -The folderOpenIcon, folderClosedIcon, and defaultLeafIcon
    properties
    -Data provider node icon fields
    -The setItemIcon() method
    -The iconFunction property
    In other words, I want to "setItemIcon" to an mx:ColorPicker,
    if that makes any sense.
    Is there a standard way of doing this? If not, how can I go
    about implementing such a control? Thanks in advance!

    well, Network UI should be used.

  • How can I set the foreground/background color after using CSPickColor()?

    Hello all,
    Is there any one who has experience on changing foreground or background color using Photoshop Plug-in SDK?
    Currently I can get a returned color from CSPickColor(), but have no idea how to use it.
    Thanks!

    You can try a linear-gradient that starts at gray 0% and ends at white <whatever the percentage the thumb is at>.
            final Node track = slider.lookup(".track");
            slider.valueProperty().addListener(new ChangeListener<Number>() {
                public void changed(ObservableValue<? extends Number> ov, Number t, Number t1) {
                    double pct = (t1.doubleValue()-slider.getMin())/(slider.getMax()-slider.getMin())*100;
                    track.setStyle("-fx-background-color: linear-gradient(to right, gray, gray " + pct + "%, white" + pct + "%, white);");
            });Edited by: dgrieve on Apr 12, 2012 12:19 PM

  • How can I create a folders of apps for multiple users?

    I use several iPads with my students and would like to set up a folder for each student. I want to place "an alias" of each app the student uses in their folder. On my Mac, I can "make alias" and place aliases in seperate folders. How can I do that on my iPad? Thanks!

    You can drag one app on top of another and make a folder. However the limit to this is, for your situation, there can be no sharing of apps....the app Fred can only be in one folder because it's only on the device once.  (so it may not work for what you need)
    and I cannot recall if you can edit the name of the folder.
    Unfortunately, for situations like yours, the iPad was created to be a single user device, so there's really not support for multiple users or multiple levels of access.

  • How can I Create a Client Configuration File for RemoteApp and Desktop Connection with Server 2012?

    I have a working RDS RemoteApp site and looking to test out the feature in Windows 7 Control Panel\All Control Panel Items\RemoteApp and Desktop Connections
    I came across this link: Create a Client Configuration File for RemoteApp and Desktop Connection and I believe this is what I need to do first, but these instructions are for
    Server 2008, and I'm running 2012.
    Any suggestions or tips on how I can begin testing this with Server 2012?

    Hi,
    You can manually enter the path to the 2012 feed and it will connect and download the RemoteApps and Desktop connections.
    If you need a sample .wcx file I have posted one here a couple of times.  If you want I will look for it and post a link.
    -TP
    I tried adding my URL's below, these are sample links that work for me right now for when I log into the web page, but neither of these work.  And I'm not sure what I would need to do with or how to create a .wcx file.
    When I type in my URL of: https://connect.mydomain.org/RDWeb, I get redirected to: 
    https://connect.mydomain.org/RDWeb/Pages/en-US/login.aspx?ReturnUrl=/RDWeb/Pages/en-US/Default.aspx

Maybe you are looking for

  • IDOC status 03 in R3 but i cant see it in XI

    Hi Experts, R3 side idoc created successfully and 03 status in we02, there were no entries in SM58, SLDCHECK also works fine, but i cant see the idoc in XI. i deleted the meta data and created again but no luck, i created port and rfc destination and

  • I'm having trouble importing photos to my Ipad2

    I followed all the instructions, attached the iPad, selected the device and hit "photos," then selected a folder (73 photos) from my PC.  Now my iTunes says it's syncing to the Ipad but it also says (unendingly) "Accessing iTunes Store."  Is this wha

  • [TV@Plus] remote issue

    I cannot seem to get the remote working. I messed with the connection several times so this is not the issue.

  • Placing Excel Spreadsheet resizing

    We are using INDCS3 and have created an Excel spreadsheet exactly to size (inches). We created a new IND document (preference set to inches) and when we do a PLACE it places the file, but shrinks it down to the columns are smaller and the fonts are t

  • IOS problem in iPhone

    Hello sir i have so many apple devices ,but now i'm found problem in iOS 7.0.4 (11B554a) & inform to your apple technical senior officer Mr. Mohammed Kamran. but i think your customer care helpline 18004250744 (india)is not give properly Response .Th