Determine the best width for ListCellRenderer - Multi-column combo box

Currently, I am having a multi column combo box. In order for the column to align properly during show popup, I use box layout to do so. However, the short coming for box layout is that, the size for each column is fixed. This makes me have a difficulty, when I have a long string to be displayed. The problem is shown through the following screen shoot.
http://i.imgur.com/4Nfc6.png
This is because in 2nd column,
1) All the 3 rows must be in same size so that they are aligned.
2) But 1st row and 2nd row cell renderer, do not know 3rd row is holding such a long string.
The code (2 files) to demo this problem is as follow. Is there any way the size of the cell will be adjusted automatically? Yet, all the row will be aligned properly.
ResultSetCellRenderer.java
package javaapplication24;
import java.awt.Color;
import java.awt.Component;
import javaapplication24.NewJFrame.ResultType;
import javax.swing.JList;
import javax.swing.ListCellRenderer;
import javax.swing.UIManager;
* @author yccheok
public class ResultSetCellRenderer extends javax.swing.JPanel implements ListCellRenderer {
    /** Creates new form ResultSetCellRenderer */
    public ResultSetCellRenderer() {
        initComponents();
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        setLayout(new javax.swing.BoxLayout(this, javax.swing.BoxLayout.X_AXIS));
        jLabel1.setText("jLabel1");
        jLabel1.setMaximumSize(new java.awt.Dimension(88, 14));
        jLabel1.setMinimumSize(new java.awt.Dimension(88, 14));
        jLabel1.setPreferredSize(new java.awt.Dimension(88, 14));
        add(jLabel1);
        jLabel2.setText("jLabel2");
        jLabel2.setMaximumSize(new java.awt.Dimension(100, 14));
        jLabel2.setMinimumSize(new java.awt.Dimension(200, 14));
        jLabel2.setPreferredSize(new java.awt.Dimension(100, 14));
        add(jLabel2);
    }// </editor-fold>
    // Variables declaration - do not modify
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    // End of variables declaration
    // Do not use static, so that our on-the-fly look n feel change will work.
    private final Color cfc  = UIManager.getColor("ComboBox.foreground");
    private final Color cbc  = UIManager.getColor("ComboBox.background");
    private final Color csfc = UIManager.getColor("ComboBox.selectionForeground");
    private final Color csbc = UIManager.getColor("ComboBox.selectionBackground");
    private final Color cdfc = UIManager.getColor("ComboBox.disabledForeground");
    // For Nimbus look n feel.
    private final Color nimbus_csfc;
         Color c = UIManager.getColor("ComboBox:\"ComboBox.renderer\"[Selected].textForeground");
         // Pretty interesting. Applying "c" directly on the component will not
         // work. I have the create a new instance of Color based on "c" to make
         // it works.
         nimbus_csfc = c != null ? new Color(c.getRed(), c.getGreen(), c.getBlue()) : null;
    private final Color nimbus_csbc;
        Color c = UIManager.getColor("ComboBox:\"ComboBox.renderer\"[Selected].background");
         // Pretty interesting. Applying "c" directly on the component will not
         // work. I have the create a new instance of Color based on "c" to make
         // it works.
        nimbus_csbc = c != null ? new Color(c.getRed(), c.getGreen(), c.getBlue()) : null;
    @Override
    public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
        final Color _csbc = csbc != null ? csbc : nimbus_csbc;
        final Color _csfc = csfc != null ? csfc : nimbus_csfc;
        this.setBackground(isSelected ? _csbc : cbc);
        this.setForeground(isSelected ? _csfc : cfc);
        jLabel1.setBackground(isSelected ? _csbc : cbc);
        jLabel1.setForeground(isSelected ? _csfc : cfc);
        jLabel2.setBackground(isSelected ? _csbc : cbc);
        jLabel2.setForeground(isSelected ? _csfc : cfc);
        final ResultType result = (ResultType)value;
        jLabel1.setText(result.symbol);
        jLabel2.setText(result.name);
        return this;
NewJFrame.java
package javaapplication24;
import java.awt.Container;
import java.awt.Dimension;
import javax.swing.JComboBox;
import javax.swing.JList;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import javax.swing.plaf.basic.BasicComboPopup;
* @author yccheok
public class NewJFrame extends javax.swing.JFrame {
    public static class ResultType {
         * The symbol.
        public final String symbol;
         * The name.
        public final String name;
        public ResultType(String symbol, String name) {
            this.symbol = symbol;
            this.name = name;
        @Override
        public String toString() {
            return symbol;
    /** Creates new form NewJFrame */
    public NewJFrame() {
        initComponents();
        this.jComboBox1.addPopupMenuListener(this.getPopupMenuListener());
        this.jComboBox1.setRenderer(new ResultSetCellRenderer());
        this.jComboBox1.addItem(new ResultType("Number 1", "Normal"));
        this.jComboBox1.addItem(new ResultType("Number 2", "Normal"));
        this.jComboBox1.addItem(new ResultType("Number 3", "A VERY VERY VERY VERY long text"));
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {
        jComboBox1 = new javax.swing.JComboBox();
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
        jComboBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox1ActionPerformed(evt);
        getContentPane().add(jComboBox1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, 110, -1));
        pack();
    }// </editor-fold>
    private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
    * @param args the command line arguments
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                final NewJFrame frame = new NewJFrame();
                frame.setVisible(true);
    private PopupMenuListener getPopupMenuListener() {
        return new PopupMenuListener() {
            @Override
            public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
                // We will have a much wider drop down list.
                adjustPopupWidth(jComboBox1);
            @Override
            public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
            @Override
            public void popupMenuCanceled(PopupMenuEvent e) {
     * Adjust popup for combo box, so that horizontal scrollbar will not display.
     * Resize JComboBox dropdown doesn't work without customized ListCellRenderer
     * http://www.camick.com/java/source/BoundsPopupMenuListener.java
     * @param comboBox The combo box
    public static void adjustPopupWidth(JComboBox comboBox) {
        if (comboBox.getItemCount() == 0) return;
        Object comp = comboBox.getAccessibleContext().getAccessibleChild(0);
        if (!(comp instanceof BasicComboPopup)) {
            return;
        BasicComboPopup popup = (BasicComboPopup)comp;
        JList list = popup.getList();
        JScrollPane scrollPane = getScrollPane(popup);
        // Just to be paranoid enough.
        if (list == null || scrollPane == null) {
            return;
        //  Determine the maximimum width to use:
        //  a) determine the popup preferred width
        //  b) ensure width is not less than the scroll pane width
        int popupWidth = list.getPreferredSize().width
                        + 5  // make sure horizontal scrollbar doesn't appear
                        + getScrollBarWidth(popup, scrollPane);
        Dimension scrollPaneSize = scrollPane.getPreferredSize();
        popupWidth = Math.max(popupWidth, scrollPaneSize.width);
        //  Adjust the width
        scrollPaneSize.width = popupWidth;
        scrollPane.setPreferredSize(scrollPaneSize);
        scrollPane.setMaximumSize(scrollPaneSize);
     *  I can't find any property on the scrollBar to determine if it will be
     *  displayed or not so use brute force to determine this.
    private static int getScrollBarWidth(BasicComboPopup popup, JScrollPane scrollPane) {
        int scrollBarWidth = 0;
        JComboBox comboBox = (JComboBox)popup.getInvoker();
        if (comboBox.getItemCount() > comboBox.getMaximumRowCount()) {
            JScrollBar vertical = scrollPane.getVerticalScrollBar();
            scrollBarWidth = vertical.getPreferredSize().width;
        return scrollBarWidth;
     *  Get the scroll pane used by the popup so its bounds can be adjusted
    private static JScrollPane getScrollPane(BasicComboPopup popup) {
        JList list = popup.getList();
        Container c = SwingUtilities.getAncestorOfClass(JScrollPane.class, list);
        return (JScrollPane)c;
    // Variables declaration - do not modify
    private javax.swing.JComboBox jComboBox1;
    // End of variables declaration
}Edited by: yccheok on Jan 13, 2011 9:35 AM

Are these two lines intentionally or is it just a mismatch?
jLabel2.setMaximumSize(new java.awt.Dimension(100, 14));
jLabel2.setMinimumSize(new java.awt.Dimension(200, 14));
2) But 1st row and 2nd row cell renderer, do not know 3rd row is holding such a long string.There is only one cell renderer for all rows, so no need for the rows to know each other.
To calculate the exact maximum width of column two, you have to check each entry.
If you can do this BEFORE creating the combo, you could do this in a loop similar to this pseudo code
FontMetrics fm= jComboBox1.getFontMetrics(jComboBox1.getFont());
foreach (column2String) {
  int length= fm.stringWidth(column2String);
  if (length>max) max= length;
}Now you have a max value to dimension jLabel2 in your renderer.
If you don't fill your combo in one go, but rather at runtime, you have to check at each
jComboBox1.addItem(...)
whether the string for label2 is extending the current max, redefine max, and repaint the combo.
This second approach I haven't done so far, but that's how I would try.

Similar Messages

  • Mult-Column Combo Box

    Hellow
    Dose anybody know how to manipulate Multi-Column Combo box in Forms 6i. for more details check this link. http://home.component1.com/img/flex7screen.jpg
    If somebody could do it before .. then please just give me some info.
    Regards
    Tariq
    null

    populate list using record group & create record group using query having multiple columns merged together through concatenatio.
    Ahmer

  • Testing for no selection of combo box - mandatory combo

    What si the best way to see if a combo box has not been selected when it does not have a default value?
    if (ocombo.Selected.Value="")

    Hi,
    some solutions
    in c#
    if (((SAPbouiCOM.ComboBox)(oForm.Items.Item("cmbUID").Specific)).Selected != null) {
    in vb6
    if (NOT(oForm.Items.Item("cmbUID").Specific.Selected is nothing)) then
    you can also try
    if( oCombobox.Selected is null)
    lg David

  • What is the best practice for inserting (unique) rows into a table containing key columns constraint where source may contain duplicate (already existing) rows?

    My final data table contains a two key columns unique key constraint.  I insert data into this table from a daily capture table (which also contains the two columns that make up the key in the final data table but are not constrained
    (not unique) in the daily capture table).  I don't want to insert rows from daily capture which already exists in final data table (based on the two key columns).  Currently, what I do is to select * into a #temp table from the join
    of daily capture and final data tables on these two key columns.  Then I delete the rows in the daily capture table which match the #temp table.  Then I insert the remaining rows from daily capture into the final data table. 
    Would it be possible to simplify this process by using an Instead Of trigger in the final table and just insert directly from the daily capture table?  How would this look?
    What is the best practice for inserting unique (new) rows and ignoring duplicate rows (rows that already exist in both the daily capture and final data tables) in my particular operation?
    Rich P

    Please follow basic Netiquette and post the DDL we need to answer this. Follow industry and ANSI/ISO standards in your data. You should follow ISO-11179 rules for naming data elements. You should follow ISO-8601 rules for displaying temporal data. We need
    to know the data types, keys and constraints on the table. Avoid dialect in favor of ANSI/ISO Standard SQL. And you need to read and download the PDF for: 
    https://www.simple-talk.com/books/sql-books/119-sql-code-smells/
    >> My final data table contains a two key columns unique key constraint. [unh? one two-column key or two one column keys? Sure wish you posted DDL] I insert data into this table from a daily capture table (which also contains the two columns that make
    up the key in the final data table but are not constrained (not unique) in the daily capture table). <<
    Then the "capture table" is not a table at all! Remember the fist day of your RDBMS class? A table has to have a key.  You need to fix this error. What ETL tool do you use? 
    >> I don't want to insert rows from daily capture which already exists in final data table (based on the two key columns). <<
    MERGE statement; Google it. And do not use temp tables. 
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

  • What is the best method for writing Multicolum​n List data to a text file?

    I am trying to find the best method for writing the data from a multicolumn list to a text file. Say the list has 7 rows and 6 columns of data. I would like the final file to have the data resemble the Multicolumn List as closely as possible with or without column headers. A sample VI showing how to accomplish this would be greatly appreciated. I realize this is pretty basic stuff, but I can get the output to the file, but it comes out with duplicate data and I am on a time crunch hense my request for help.
    Thank You,
    Charlie
    Everything is Free! Until you have to pay for it.

    Hello,
    I think that the answer to your question it's on the example that I've made right now.
    See the attached files....
    Software developer
    www.mcm-electronics.com
    PS: Don't forget to rate a good anwser ; )
    Currently using Labview 2011
    PORTUGAL
    Attachments:
    Multi.vi ‏12 KB
    Multi.PNG ‏6 KB

  • How do you determine the optimal size for Mozilla Firefox?

    How do you determine the optimal size for cache in Mozilla
    Firefox? I am using Firefox 7.0.1 on a 64-bit Windows 7 Ultimate operating system with 3GB RAM and 300 GB hard drive, but I have other computers running Windows XP. If the answer doesn't apply to all current versions of Firefox on all supported Windows operating systems, please explain the differences. Is there a formula for calculating the best cache size?

    I found that the best idea is to let Firefox decide that itself.

  • How to determine the mount point for directory /tmp ?

    Folks,
    Hello. I am installing Oracle 11gR2 RAC using 2 Virtual Machines (rac1 and rac2 whose OS are Oracle Linux 5.6) in VMPlayer and according to the tutorial
    http://appsdbaworkshop.blogspot.com/2011/10/11gr2-rac-on-linux-56-using-vmware.html
    I am installing Grid infrastructure. I am on step 7 of 10 (verify Grid installation enviroment) and get this error:
    "Free Space: Rac2: /tmp"
    Cause: Could not determine mount point for location specified.
    Action: Ensure location specified is available.
    Expected value: n/a
    Actual value: n/a
    I have checked the free space using the command:
    [root@Rac2 /]# df -k /tmp
    Output:
    Filesystem     1k-blocks     used     Available     Use%     Mounted on
    /dev/sda1     30470144     7826952     21070432     28%     /
    As you see above, the free space is enough, but could not determine mount point for /tmp.
    Do any folk understand how to determine the mount point for directory /tmp ?
    Thanks.

    I have just checked "/home/oracle/.bash_profile". But in my computer, there is no "oracle" under /home directory.Is this your first time Linux and Oracle installation? I had a brief look at your referenced link. The reason why you do not find a "oracle" user is because the instructions use "ora11g" instead, which, btw, is not standard. The directories of your installation and your installation source can be somewhat different from known standards and you will have to adjust it to your system.
    My best guess is that you have either missed something in the instructions or you need to ask the author of the blog what is wrong. The chance to find someone here who has experience with these custom instructions is probably unlikely.
    I suggest you try to locate the cluster verification tool, which should be in the bin directory of your grid installation. Alternatively you might want to check the RAC, ASM & Clusterware Installation forum: RAC, ASM & Clusterware Installation

  • What is the Best practice for ceramic industry?

    Dear All;
    i would like to ask two questions:
    1- which manufacturing category (process or discrete) fit ceramic industry?
    2- what is the Best practice for ceramic industry?
    please note from the below link
    [https://websmp103.sap-ag.de/~form/sapnet?_FRAME=CONTAINER&_OBJECT=011000358700000409682008E ]
    i recognized that ceramic industry is under category called building material which in turn under mill product and mining
    but there is no best practices for building material or even mill product and only fabricated meta and mining best practices is available.
    thanks in advance

    Hi,
    I understand that you refer to production of ceramic tiles. The solution for PP was process, with these setps: raw materials preparation (glazes and frits), dry pressing (I don't know extrusion process), glazing, firing (single fire), sorting and packing. In Spain, usually are All-in-one solutions (R/3 o ECC solutions). Perhaps the production of decors have fast firing and additional processes.
    In my opinion, the curiosity is in batch determination in SD, that you must determine in sales order because builders want that the order will be homogeneus in tone and caliber, and he/she can split the order in diferents deliveries. You must think that batch is tone (diferents colours in firing and so on) and in caliber.
    I hope this helps you
    Regards,
    Eduardo

  • How to determine the proper size for Oracle 8i Data Base Objects

    Hi,
    I'm working on an Oracle 8i Data base. I'd like to know how to determine the proper size for the Data Base objects such as tables, datafiles, tablespaces...
    Thanks.

    Start with the docs.
    http://download-west.oracle.com/docs/cd/A87860_01/doc/server.817/a76956/schema.htm#949
    Best Regards
    Krystian Zieja / mob

  • What is the best laptop for Photoshop Elements 10 ?

    I have HP Pavilion g6 Notebook,i5-245M 2.5GHZ, 4 GB mwmory, 64-bit Operating system window 7, Radeon Graphics, Eidtior not working , I get error message ( Unable to continue because of hardware or system error,Sorry,but this error in unercoverable).
    So I want to give this one to my son, and I want to bay new One for me,
    but i do not want to have same Error with my new Laptop,
    So any one know what is the best Laptop for PhotoShop Elements 10 ?
    Thanks for Helping me .

    I would suggest a machine with a multi-core processor and plenty of storage as photo files take up quite a lot of room over time. Many laptops have a screen resolution of 1366 x 768 and whilst elements will run OK some menu functionality will be missing if the display is not at least 800 pixels in height. A resolution of 1600 x 900 would be much better.
    Independent advice is best, such as Which, UK. You can get a trial membership for as little as £1 to access their recommendations.
    http://www.which.co.uk/technology/computing/reviews/laptops/best-buy/verdict/

  • What is the best program for designing event flyers? I am looking for something basic and simple.

    What is the best program for designing event flyers? I am looking for something basic and simple.

    Poor old Photoshop® is forever being put down when it comes to layout work, but it is perfectly capable, and can output a high quality print PDF the printer will be perfectly happy with.  OK you don't have the text flow between columns bells and whistles of InDesign and [spit] Publisher, but if you have a $10/month Photoshop/Lightroom subscription, instead of the $50/month full subscription, don't think you can't do a perfectly good flyer or poster.
    https://helpx.adobe.com/photoshop/how-to/align-objects-guides.html

  • Error when determining the CTIADM_PROF profile for agent xyz

    Hi,
    I have created the new cic frame work and assigned it to the position. when i run the TC - cic0, I am getting the following
    "Error when determining the CTIADM_PROF profile for agent xyz"
    Can you help me out ?
    Thanks in advance

    Hi Devi,
    Problem is your IC winclient profile definition don't have any profile definition for CTIAMD_PROF assigned to it.
    For this you can use standard profiles or may create your own CTI Component profile.
    Follow IMG path:
    Customer Relationship Managemet>Interaction Center WinClient>Component Configuration>Hidden Components>Configuration of CTI Component-->Define CTI Component Profile
    Use this profile defintion to assign it to CTIAMD_PROF in you IC winclient profile definition.
    Best Regards,
    Pratik Patel
    <b>Reward with POints!</b>

  • What's the best fix for a slow computer?

    What's the best fix for a slow computer?

    What model computer? What are your primary uses and apps?
    First thing anyone can do is replace or upgrade the system boot drive to SSD. Makes a very nice improvement.
    How new or old is it? What version of OS X is it running?
    Maybe it won't run faster but could run better with more RAM.
    Take a look at all the tabs in Activity Monitor. If not on the Dock, go into Applications/Utilities and open it and keep it on the dock. Can tell you what is using your processor the most, RAM usage, disk and network I/O.
    Don't install things that aren't needed. That can be counter intuitive to some but 'less is more' and some just really pull a computer system down. Security programs, "clean up programs" and others.
    General purpose Mac troubleshooting guide:
    Isolating issues in Mac OS X
    Creating a temporary user to isolate user-specific problems:
    Isolating an issue by using another user account
    Identifying resource hogs and other tips:
    Using Activity Monitor to read System Memory and determine how much RAM is being used
    Starting the computer in "safe mode":
    Mac OS X: What is Safe Boot, Safe Mode?
    To identify potential hardware problems:
    Apple Hardware Test
    General Mac maintenance:
    Tips to keep your Mac in top form

  • What is the best easy setup for d600 nikon. and what is the best export for hd movie, 11 min ?

    i'm exporting my movie in mpeg4, 1960X1080, for streaming.
    all the movie is going well, but there is some cubes in the sky, and also, some frames jumpes.
    I treid few times, but its always the same.
    Thank you,Lena

    You should transcode the Nikon clips to Pro Res 422 before you import them to your project. That can be done in Compressor or MPEG Streamclip. Let FCP automatically determine the best sequence settings, based on your first clip.   Export your project as Quick Time Movie, current settings. If you need an MP4 with h.264, MPEG Streamclip can make it for you.
    Russ

  • Error while determining the currency types for PO

    Hi,
    When running MR11 on PO4534356339 (account maintenance) the following error msg appears:
    Error while determining the currency types for 4534356339 00030.
    Message no.C+171
    Check the configuration.
    I have checked all currency settings and found ok. Material ledger is activated for this plant. It looks like there is problem in Item 30 of the Purchase order is having problem.
    Best Regards,
    MR

    Hi,
    Please refer this link :
    MR11 error - Error while determining currency type - C+, 171!!!
    Regards,
    Pramitha.

Maybe you are looking for

  • Flash Remoting -  connection/server errors

    Hi people, I would like to catch the error in the client-aplication (Flash) and give the user a friendly msg when the server is unavaliable ( due to connetion problems / connection timeout). For that kind of error I get nothing in the FaultEvent Obje

  • Mac mini - 649 days to go for back up to complete!!

    Hi I've had my new Mac mini for 1 week now and have still yet to complete a back up to my reformatted external hard drive. The back up shows to be in progress, but states there is approximately 649 days to go to complete back up. It would be quicker

  • Spool report line width in background jobs

    Hi All, I wrote a report and specified the line size in the report header: REPORT /sappssrm/option_handler NO STANDARD PAGE HEADING LINE-SIZE 185. I want to run this report as background job and get a spool list with results of the report. I expected

  • Easiest way to pass GET parameters to applet - Javascript really required??

    I want to transfer GET parameters to an appelt, i.e. in the call http://***/test.html?param1=abc&param2=def the param/values should be available in the applet. After some searching I've got the impression that this requires Javascript (http://stackov

  • Problem connecting my blog with

    HI, I am trying to connect my blog http://organic-beauty-recipes.com/ (originally homemadeorganicbeautyrecipes.wordpress.com) to adobe contribute but with no success. my blog is still hosted by wordpress; I just paid the upgrade to get a domain name.