Avoid resize of JList with setFixedCellWidth

I have functionality in my application such that when I select an item in one list, information that is associated with the item appears in a second list. I notice however that the width of this second list box is changing according to the contents of the list. The result is that each time I select an item in the first list, the second list changes size.
I have tried using two methods, setFixedCellWidth(int value) and setPrototypeCellValue(" ") to control this behaviour. But the consequence is that although the second list does not change size, it also does not update with the information that is associated with the selected item in the first list.
So my question is how do these methods effect the repaint and revalidation of the panel when the listmodel of the list is updated?
Thanks so much.

Excuse dupe post if there is one. You have other problems if you are not seeing updates in second list when using setProto. . . method. See Below:
public class ListTest extends JFrame {
    Label label;
    DefaultListModel model;
    DefaultListModel targetModel;
    JList testList;
    JList targetList;
    public static void main( String[] args){
        new ListTest();
    public ListTest(){
        //super("Closing Test");
        getContentPane().setLayout(new BorderLayout());
        model = new DefaultListModel();
        for (int i = 0 ; i < 10 ;i++){
            model.addElement("test "+i);
        testList = new JList(model);
        testList.setDragEnabled(true);
        testList.setPrototypeCellValue("                                 ");
        testList.setTransferHandler(new ListTransferHandler());
        targetModel = new DefaultListModel();
        targetModel.addElement("test 6");
        testList.addListSelectionListener(new ListSelectionListener(){
            public void valueChanged(ListSelectionEvent lse){
                System.out.println(((String)testList.getSelectedValue()));
         JPanel centerPanel = new JPanel(new GridLayout(0,2,5,5));
        targetList = new JList(targetModel);
        targetList.setPrototypeCellValue("                                 ");
        targetList.setDragEnabled(true);
        targetList.setTransferHandler(new ListTransferHandler());
        JScrollPane targetJsp = new JScrollPane(targetList);
        JScrollPane jsp = new JScrollPane(testList);
        centerPanel.add(jsp);
        centerPanel.add(targetJsp);
        getContentPane().add(centerPanel);
        //setSize(200,300);
        addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent we){
                setVisible(false);
                dispose();
                System.exit(0);
        JPanel buttonPanel = new JPanel();
        JButton addButton = new JButton("add");
        addButton.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                Object[] selections = testList.getSelectedValues();
                for (int counter = 0 ; counter < selections.length; counter++){
                    String tester = (String)selections[counter];
                    targetModel.addElement(selections[counter]);
        JButton subButton = new JButton("subtract");
        subButton.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                if ( targetList.getSelectedIndex() >= 0){
                    targetModel.removeElementAt(targetList.getSelectedIndex());
        buttonPanel.add(addButton);
        buttonPanel.add(subButton);
        getContentPane().add(buttonPanel, BorderLayout.SOUTH);
                setVisible(true);
        pack();
}Cheers
DB

Similar Messages

  • Resizing a JList with variable row heights, not updating the "picture"

    Firstly I would like to apologize for posting this Swing question here, but I was unable to find the Swing category, if someone could direct me to that I would be most grateful.
    Ok, so in abstract what I am trying to do is have a JList with resizable rows to act as a row header for a JTable (exactly like the row headers in OO Calc or MS Excel).
    What I have is a RowHeaderRenderer:
    public class RowHeaderRenderer extends JLabel implements ListCellRendererand it has a private member:
    private Vector<Integer>        _rowHeights            = new Vector<Integer>();which contains a list of all the variable row heights.
    Then there is my getListCellRendererComponent method:
        public Component getListCellRendererComponent(    JList         list,
                                                          Object        value,
                                                          int           index,
                                                          boolean       isSelected,
                                                          boolean       cellHasFocus)
            // Make sure the value is not null
            if(value == null)
                this.setText("");
            else
                this.setText(value.toString());
            // This is where height of the row is actually changed
            // This method is fed values from the _rowHeights vector
            this.setPreferredSize(new Dimension(this.getPreferredSize().width, _rowHeights.elementAt(index)));
            return this;
        }And then I have a row header:
    public class RowHeader extends JList implements TableModelListener, MouseListener, MouseMotionListenerand you may be interested in its constructor:
        public RowHeader(JTable table)
            _table = table;
            _rowHeaderRenderer = new RowHeaderRenderer(_table);
            this.setFixedCellWidth                        (50);
            this.setCellRenderer                        (_rowHeaderRenderer);
            // TODO: grab this value from the parent view table
            JScrollPane panel = new JScrollPane();
            this.setBackground(panel.getBackground());
            this.addMouseMotionListener                    (this);
            this.addMouseListener                        (this);
            this.setModel                                (new DefaultListModel());
            table.getModel().addTableModelListener        (this);
            this.tableChanged                            (new TableModelEvent(_table.getModel()));
        }and as you can see from my mouse dragged event:
        public void mouseDragged(MouseEvent e)
            if(_resizing == true)
                int resizingRowHeight = _rowHeaderRenderer.getRowHeight(_resizingRow);
                _rowHeaderRenderer.setRowHeight(_resizingRow, resizingRowHeight + (e.getPoint().y - _cursorPreviousY));
                _cursorPreviousY = e.getPoint().y;  
        }all I am doing is passing the rowHeaderRenderer the values the currently resizing row should be, which works fine. The values are being changed and are accurate.
    The issue I am having is that while this dragging is going on the row does not appear to be resizing. In other words the "picture" of the row remains unchanged even though I change the values in the renderer. I tried calling:
    this.validate();and
    this.repaint();at the end of that mousedDragged method, but to no avail, neither of them worked.
    Again, I verified that I am passing the correct data in the RowHeaderRenderer.
    So, anyone have any ideas how I should get the image of the RowHeader (JList) to update after calling my MouseDragged event?
    Thank you for your time,
    Brandon

    I was able to fix this some time ago. Here is the solution:
         public void mouseDragged(MouseEvent e)
              if(_resizing == true)
                   int newHeight = _previousHeight + (e.getPoint().y - _cursorPreviousY);
                   if(newHeight < _minRowHeight)
                        newHeight = _minRowHeight;
                   _rowHeaderRenderer.setRowHeight(_resizingRow, newHeight);
                   _table.setRowHeight(_resizingRow, newHeight);
              this.updateUI();
         }

  • Populating JList with a single database column

    Hi all,
    I have the following code and i'm trying to popluate the JList with a particular colum from my MySQL Database..
    how do i go about doing it??
    Can some one please help
    import java.awt.*; import java.awt.event.*; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.swing.*; public class RemoveD extends JDialog {     private JList list;     private JButton removeButton;     private JScrollPane scrollPane;     private Connection conn = null;     private Statement stat = null;         public RemoveD(Frame parent, boolean modal) {         super(parent, modal);         initComponents();     }     private void initComponents() {         scrollPane = new JScrollPane();         list = new JList();         removeButton = new JButton();         setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);         getContentPane().setLayout(new GridLayout(2, 0));         scrollPane.setViewportView(list);         getContentPane().add(scrollPane);         removeButton.setText("Remove");         removeButton.addActionListener(new ActionListener() {             public void actionPerformed(ActionEvent evt) {                 removeButtonActionPerformed(evt);             }         });         getContentPane().add(removeButton);         pack();         try {             Class.forName("com.mysql.jdbc.Driver");                    } catch (ClassNotFoundException ex) {             ex.printStackTrace();                    }         try {             String userID = "";             String psw = "";             String url;             url = "jdbc:mysql://localhost:3306/names";             conn = DriverManager.getConnection(url, userID, psw);             stat = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,                     ResultSet.CONCUR_READ_ONLY);             stat.close();             conn.close();         } catch (SQLException ex) {             ex.printStackTrace();         }     }     private void removeButtonActionPerformed(ActionEvent evt) {     }     public static void main(String args[]) {         EventQueue.invokeLater(new Runnable() {             public void run() {                 RemoveD dialog = new RemoveD(new JFrame(), true);                 dialog.addWindowListener(new WindowAdapter() {                     public void windowClosing(WindowEvent e) {                         System.exit(0);                     }                 });                 dialog.setVisible(true);             }         });     } }

    I figured out how to do it

  • How to avoid starting a page with line breaks?

    Hello. I've just started to refine my Master's thesis and some of the topics moved up and down as I edited their contents. The problem is that in some cases the topic breaks right after the title, and the rest of the contents just move away to another page. Is there any way to avoid starting a page with line breaks or broken topics?

    At the end of your title, you didn't inserted a line break but a paragraph break (carriage return).
    Acivate the mode "Show hidden characters"
    Select the carriage return (paragraph break)
    Delete it
    Press Shift + return to insert a true line break.
    It may be useful to apply that several times if you inserted several carriage returns between the title and the first filled line.
    Yvan KOENIG (VALLAURIS, France) 15 mai 2011 19:40:14

  • JTable/jlist with word wrapping cells?

    Hello all,
    I got a simple looking problem but i can't seem to find any working solution for it:
    A jtable or jlist with cells that wordwrap text (cells differ in height).
    I found many examples on groups.google and this forum but they all seem to suffer a 100% processor load when 2 or more cells differ in height.
    Can anyone point me to a working example?
    Kind regards,
    Twan

    Thanks! That's a real live saver.
    I had been looking for a solution for several days, strange google did not yet found the mentioned page, cause it contains usefull information.
    I've just implemented the multiline table and it works without any problems and most important without 100% cpu usage.
    The bucks are comming your way ;-)

  • So simple, yet so annoying: problem resizing anchored frame with grab bars

    Asked a question yesterday on how to 'snug' an anchored frame to an image. Got the answer and it works great (Esc-m-p)
    Now... the reason I needed to do this is that when I try to resize a frame with the grab bars, it 'jerks' as I move vertically or horizontally.
    What that means is...
    With borders on, the frame border is a dotted line.
    If I grab the left side of a frame and move my mouse to the right to make the frame smaller, the border doesn't move smoothly -- it jumps a distance of about 1.5 of those dotted lines. Thus I can't always make the frame fit nicely.
    Talked to another Frame user and she said that her's drags smoothly.
    So... am I missing a setting somewhere? Any thoughts would be greatly appreciated.

    ##&*!
    I was working over a VPN when I first experienced the problem... everything was slower than molasses. Set Snap off, did some other work, Frame crashed.
    Setting didn't persist, but everything had taken so long I forgot to check it.
    Gah. Yes, Snap off works wonders when it's *actually* off.

  • Populatin a JList with elements from a DB (access here)

    last year i was able to populate a JList with data from a database
    however this year something doesnt work
    this is last year
    public String[] getOnderwerpen()
    System.out.println(theConnection==null?" connection null ":" connection niet null ");
    String []locaties = new String[30];
    ArrayList returnLijst;
    returnLijst = new ArrayList();
    ArrayList arraylist;
    arraylist = new ArrayList();
              String[] deLocaties = null;
    try{
    String onderwerpQuery = "SELECT OnderwerpID FROM Onderwerp order by OnderwerpID";
    Statement statement = theConnection.createStatement();
    System.out.println(statement==null?" statement null ":" statement niet null ");
    statement.execute(onderwerpQuery);
    ResultSet result = statement.getResultSet();
    System.out.println(result==null?" ResultSet null ":" ResultSet niet null ");
    int i = 0;
                   while(result.next())
              //          locaties[i] = result.getString("OnderwerpID");
    locaties[i] = result.getString("OnderwerpID");
                                            i++;
    deLocaties = new String;
              for (int j=0;j<deLocaties.length;j++)
                   deLocaties[j] = locaties[j];
              sorteerStringArray(deLocaties);
    }//end-try
    catch (Exception e) {
    e.printStackTrace();
    return deLocaties;
    & this is what i did this year
    public String[] getbedrijfNaam()
              String[] bedrijfsNamen = new String[Constanten.aantalBedrijven];
              String[] deBedrijfsNamen = null;
         System.out.println(theConnection==null?" connection null ":" connection niet null ");
         System.out.println("test this");
         try{
         String onderwerpQuery = "SELECT naam FROM organisatie";
         Statement statement = theConnection.createStatement();
         System.out.println(statement==null?" statement null ":" statement niet null ");
         statement.execute(onderwerpQuery);
         ResultSet result = statement.getResultSet();
         int i = 0;
                        while(result.next())
                             bedrijfsNamen[i] = result.getString();
                                                 i++;
                        deBedrijfsNamen = new String[i];
                   for (int j=0;j<deBedrijfsNamen.length;j++)
                        deBedrijfsNamen[j] = bedrijfsNamen[j];
                   sorteerStringArray(deBedrijfsNamen);
                   statement.close();
                   //theConnection.close();
         }//end-try
         catch (Exception e) {
         e.printStackTrace();
         return deBedrijfsNamen;
    is there something here thats not right
    or does this no longer work because of the changes made in 1.5

    last year i was able to populate a JList with data from a database
    however this year something doesnt work
    this is last year
    public String[] getOnderwerpen()
    System.out.println(theConnection==null?" connection null ":" connection niet null ");
    String []locaties = new String[30];
    ArrayList returnLijst;
    returnLijst = new ArrayList();
    ArrayList arraylist;
    arraylist = new ArrayList();
              String[] deLocaties = null;
    try{
    String onderwerpQuery = "SELECT OnderwerpID FROM Onderwerp order by OnderwerpID";
    Statement statement = theConnection.createStatement();
    System.out.println(statement==null?" statement null ":" statement niet null ");
    statement.execute(onderwerpQuery);
    ResultSet result = statement.getResultSet();
    System.out.println(result==null?" ResultSet null ":" ResultSet niet null ");
    int i = 0;
                   while(result.next())
              //          locaties[i] = result.getString("OnderwerpID");
    locaties[i] = result.getString("OnderwerpID");
                                            i++;
    deLocaties = new String;
              for (int j=0;j<deLocaties.length;j++)
                   deLocaties[j] = locaties[j];
              sorteerStringArray(deLocaties);
    }//end-try
    catch (Exception e) {
    e.printStackTrace();
    return deLocaties;
    & this is what i did this year
    public String[] getbedrijfNaam()
              String[] bedrijfsNamen = new String[Constanten.aantalBedrijven];
              String[] deBedrijfsNamen = null;
         System.out.println(theConnection==null?" connection null ":" connection niet null ");
         System.out.println("test this");
         try{
         String onderwerpQuery = "SELECT naam FROM organisatie";
         Statement statement = theConnection.createStatement();
         System.out.println(statement==null?" statement null ":" statement niet null ");
         statement.execute(onderwerpQuery);
         ResultSet result = statement.getResultSet();
         int i = 0;
                        while(result.next())
                             bedrijfsNamen[i] = result.getString();
                                                 i++;
                        deBedrijfsNamen = new String[i];
                   for (int j=0;j<deBedrijfsNamen.length;j++)
                        deBedrijfsNamen[j] = bedrijfsNamen[j];
                   sorteerStringArray(deBedrijfsNamen);
                   statement.close();
                   //theConnection.close();
         }//end-try
         catch (Exception e) {
         e.printStackTrace();
         return deBedrijfsNamen;
    is there something here thats not right
    or does this no longer work because of the changes made in 1.5

  • Drawning text/images in a JPanel and then resizing/moving it with the mouse

    Hello ebverybody!
    I need to be able to draw some text objects in a JPanel and then resize/move it with the mouse... How could I do that!? Same for some images loaded from jpg files...
    Should I just paint the text and then repaint when the mouse selects it? How to do this selection?! Or should use something like a jLabel and then change it`s font metrics?!
    I need to keep track of the upper left corner of the text/image, as well as the width/height of it. This will be recorded in a file.
    The text/images need to smoothly move around the panel as the mouse drags when selectin an entity.. not just "click the entity, then click another point and the entity appears there as if by magic...":)
    Please, tell the best way to do that!
    Thanks everybody!
    Message was edited by:
    cassio.marques

    I know what you mean! This happened to me as well!
    And one thing that I found useful is, if you want to directly select a layer without selecting from the layers pallete and without having autoselect enabled, just hold Ctrl and click on in directly in the image. This saved me a lot of time!

  • Synchronize JList with JScrollPane

    hi all,
    I want to automatically move the scroll in the JScrollPane when I change the selected position in the JList with setSelectedIndex, right now the list is correctly selected, but the scroll remains on the top, how could I move it to position the list to see the selected item?
    thanks!
    mykro

    JComponent has a scrollRectToVisible method you could use along with JList's getCellBounds method. Maybe register a ListSelectionListener with the list, then in valueChanged get the newly selected cell's bounds from getCellBounds and call scrollRectToVisible on the JList with the cell bounds.

  • Traversing JList with arrow keys

    I've got a small problem when i try to traverse a JList with the arrow keys. When I'm at the first index of the list and press the UP arrow, I want to select the last index of the list.
    switch (keyCode){
            case VK_UP:
                    if(list.isSelectedIndex(list.getFirstVisibleIndex()))
                        list.setSelectedIndex(list.getLastVisibleIndex());
                    break;
    }When I use this code, the program selects the second last index (not the last). How can I fix this problem?
    Any suggestions will be appreciated.

    I found this thread useful but ultimately solved this another way using key binds. Maybe someone will find this useful.
    public MyDialogConstructor() {
        bindKeys();
    private void bindKeys() {
              InputMap inputMap = getJList().getInputMap(JComponent.WHEN_FOCUSED);
              KeyStroke key = KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0);
              inputMap.put(key, "jlist:UP");
              getJList().getActionMap().put("jlist:UP", new AbstractAction() {
                   private static final long serialVersionUID = 1L;
                   public void actionPerformed(ActionEvent e) {
                        if (getJList().isSelectedIndex(getJList().getFirstVisibleIndex())) {
                             getJList().setSelectedIndex(getJList().getLastVisibleIndex());
                        } else {
                             getJList().setSelectedIndex(getJList().getSelectedIndex() - 1);
              key = KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0);
              inputMap.put(key, "jlist:DOWN");
              getJList().getActionMap().put("jlist:DOWN", new AbstractAction() {
                   private static final long serialVersionUID = 1L;
                   public void actionPerformed(ActionEvent e) {
                        if (getJList().isSelectedIndex(getJList().getLastVisibleIndex())) {
                             getJList().setSelectedIndex(getJList().getFirstVisibleIndex());
                        } else {
                             getJList().setSelectedIndex(getJList().getSelectedIndex() + 1);
         }

  • HT1549 I don't want other computers connect with my computer, I don't want sharing my macbook pro, so how I can protect my computer and avoid other people connect with my computers

    I don't want other computers connect with my computer, I don't want sharing my macbook pro, so how I can protect my computer and avoid other people connect with my computers

    As long as you do not enable Sharing of any kind (System Preferences > Sharing) no other computer can connect with yours. Also make sure you have your wireless network protected with a WPA2 password.
    That's all I can suggest without knowing what OS version you are running (you are not running iOS as that is for iDevices).

  • I am working on Security scan(to avoid cross site forgery) with the CSRF approach of tomcat(apache-tomcat-6.0.32) but I am getting following issue with firefox:

    I am working on Security scan(to avoid cross site forgery) with the CSRF approach of tomcat(apache-tomcat-6.0.32) but I am getting following issue with firefox:
    1. Firefox is not supporting CSRF provided by tomcat in a proper way firefox creating multiple sessions.
    2. Whenever any exception (like JSP exception) comes on page. Firefox redirects it to CSRFPreventionFilter and this filter creates new session.
    3. Sometimes while traversing through application also CSRFPreventionFilter filter creates new session.

    I seem to have fixed it by putting <div  class="clearfloat"></div> after the navigation bar?

  • [svn:fx-trunk] 8192: Fix resizing a window with the gripper.

    Revision: 8192
    Author:   [email protected]
    Date:     2009-06-24 12:37:55 -0700 (Wed, 24 Jun 2009)
    Log Message:
    Fix resizing a window with the gripper.
    WindowedApplication.as, Window.as
    After the click on the gripper is detected and the resized is started just return. The code was falling into the hit testing for the application border.
    QE Notes: none.
    Doc Notes: none.
    Bugs: SDK-21631
    Reviewer: Glenn
    tests: checkintests
    Ticket Links:
        http://bugs.adobe.com/jira/browse/SDK-21631
    Modified Paths:
        flex/sdk/trunk/frameworks/projects/airframework/src/spark/components/Window.as
        flex/sdk/trunk/frameworks/projects/airframework/src/spark/components/WindowedApplication. as

  • JList with aligned pictures

    What would be the best way to make a JList with a picture for each item?
    I have all the pictures loaded as ImageIcons btw.

    Write a custom list renderer, see http://java.sun.com/j2se/1.4.1/docs/api/javax/swing/ListCellRenderer.html
    Then, to get the text aligned, you'll need to use the setIconTextGap method of JLabel. If the maximum icon width is 16 and your current icon is 13 pixels wide, then just set the icon-text-gab to 3.
    Something like this:
    import java.awt.*;
    import javax.swing.*;
    public class Dummy
         public static void main(String [] args)
              JList list = new JList(new Object[]{
                   new JLabel("small", new ImageIcon("d:/java/resources/java logo 16x16.png"), JLabel.LEFT),
                   new JLabel("large", new ImageIcon("d:/java/resources/java logo 32x32.png"), JLabel.LEFT)
              list.setCellRenderer(new MyCellRenderer());
              JFrame f = new JFrame();
              f.getContentPane().add(list);
              f.setSize(400,400);
              f.setVisible(true);
         static class MyCellRenderer extends JLabel implements ListCellRenderer
              public MyCellRenderer()
                   setOpaque(true);
              public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus)
                   JLabel label = (JLabel)value;
                   setText(label.getText());
                   setIconTextGap(4 + 32 - label.getIcon().getIconWidth());
                   setIcon(label.getIcon());
                   setBackground(isSelected ? Color.red : Color.white);
                   setForeground(isSelected ? Color.white : Color.black);
                   return this;

  • JList with Images for solitaire?

    could i use JList with gif images of cards for Solitaire(klondike)? if i have 7 vertical panes and one JList in each pane? or is this impossible?

    but that solution didnt work for me1) Where in the posting did you state that?
    2) if it doesn't work then you are doing something wrong.
    I think you have a better chance with your original approach. I don't see how a JList would work.

Maybe you are looking for

  • Dented my Macbook Pro and now it won't start up.  Please Help!

    Hello. I have searched and searched and cannot find a solution. Last night I was putting the finishing touches on my dissertation and accidentally dropped a tape dispenser on my 1-year-old MacBook Pro - it hit just to the left of the trackpad and lef

  • Printing issues on Brother mcc-8440 and hp laser jet 4200 in 10.8.3

    I apologize if this constitutes a double posting, but I inadvertently his the button indicating that this had been solved when it has not. for the last two weeks or so my hp 4200 prints ".8.3 (Build 12D78) Quartz PS Context)" and then blank pages in

  • Creating Mitigation Control from CUP

    Hi Guys, Is this feature implemented in Access Control???? Or Stills as enhancement

  • 1.1 performance question

    In the read me file I found this: Lightroom may experience decreased performance when the preference to Update XMP Automatically is turned on in the preferences. But when I look in preferences I don't see an option to change this. For me 1.1 is alot

  • Spanish keyboard in KDE 3.5.4

    Hello! I've a problem with my keyboard in kde. I've installed 0.7.2 version. The problem is with spanish characters ñÑ, á, é, .... When i type those characters kde show a square instead of character. This is only kde problem, in console mode and in g