JList repaint()

I can't post all my code because it is a very large jumble of crap...but here is the situation:
-I have a "fillList()" method that returns a String [] of information retrieved from a SQL query. (the size can be different with a max size of 10 every time I call fillList())..this method works fine.
-I have a frame that creates a window with some buttons a picture and a JList in the constructor by simple getContentPane().add(<component>); (I'll worry about layout later).
-One of these buttons (next10) updates the JList. Here is the code in the event handler:
resultList = new JList(fillList(data.query));
resultScrollPane = new JScrollPane(resultList);
resultsPanel = new JPanel();
resultsPanel.add(resultScrollPane, "North");
resultsPanel.add(prev10, "South");
if(numResultsLeft > 0) 
  resultsPanel.add(next10, "South");
getContentPane().add(resultsPanel, "North");
repaint();oh, and the variables are the following types:
-resultList is a JList
-resultScrolPane is a JScrollPane
-resultsPanel is a JPanel
-(Am I being too obvious yet?)
-next10 is a JButton
-prev10 is a JButton
Now I've tried this a bunch of different ways, and I can't seem to get the JList info to change. I know the data is passed correctly because when I click the JList...well, the right stuff happens at the right indexes...but the old information is still displayed.

You the man! Sweet! Yeah, I'm using set functions for everything else that updates, but I didn't know JLists have one too. Super Sweet! Much Thanks!

Similar Messages

  • Highlighting JList Items

    Hello
    Could anybody let me how to change the color of Few Items of JList. I know how to change the foreground color of an item which is selected. But, I need to show few items of JList in different color.
    Thanks in advance

    please can you tell us where is/are ..., could you able to demostrate your issue, now
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class JListDisabledItemDemo implements ItemListener, Runnable {
        private static final String ITEMS[] = {
            "Black", "Blue", "Green", "Orange", "Purple", "Red", "White", "Yellow"};
        private JList jList;
        private JCheckBox[] checkBoxes;
        private boolean[] enabledFlags;
        @Override
        public void run() {
            JPanel pnlEnablers = new JPanel(new GridLayout(0, 1));
            pnlEnablers.setBorder(BorderFactory.createTitledBorder("Enabled Items"));
            checkBoxes = new JCheckBox[ITEMS.length];
            enabledFlags = new boolean[ITEMS.length];
            for (int i = 0; i < ITEMS.length; i++) {
                checkBoxes[i] = new JCheckBox(ITEMS);
    checkBoxes[i].setSelected(true);
    checkBoxes[i].addItemListener(this);
    enabledFlags[i] = true;
    pnlEnablers.add(checkBoxes[i]);
    jList = new JList(ITEMS);
    jList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    jList.setSelectionModel(new DisabledItemSelectionModel());
    jList.setCellRenderer(new DisabledItemListCellRenderer());
    jList.addListSelectionListener(new ListSelectionListener() {
    @Override
    public void valueChanged(ListSelectionEvent e) {
    if (!e.getValueIsAdjusting()) {
    System.out.println("selection");
    JScrollPane scroll = new JScrollPane(jList);
    scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
    scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
    JFrame f = new JFrame("JList and Colors");
    Container contentPane = f.getContentPane();
    contentPane.setLayout(new GridLayout(1, 2));
    contentPane.add(pnlEnablers);
    contentPane.add(scroll);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setSize(240, 280);
    f.setLocationRelativeTo(null);
    UIManager.put("List.background", Color.red);
    UIManager.put("List.selectionBackground", Color.orange);
    UIManager.put("List.selectionForeground", Color.blue);
    UIManager.put("Label.disabledForeground", Color.magenta);
    SwingUtilities.updateComponentTreeUI(f);
    f.setVisible(true);
    @Override
    public void itemStateChanged(ItemEvent event) {
    JCheckBox checkBox = (JCheckBox) event.getSource();
    int index = -1;
    for (int i = 0; i < ITEMS.length; i++) {
    if (ITEMS[i].equals(checkBox.getText())) {
    index = i;
    break;
    if (index != -1) {
    enabledFlags[index] = checkBox.isSelected();
    jList.repaint();
    public static void main(String args[]) {
    SwingUtilities.invokeLater(new JListDisabledItemDemo());
    private class DisabledItemListCellRenderer extends DefaultListCellRenderer {
    private static final long serialVersionUID = 1L;
    @Override
    public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
    if (enabledFlags[index]) {
    return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
    Component comp = super.getListCellRendererComponent(list, value, index, false, false);
    comp.setEnabled(false);
    return comp;
    private class DisabledItemSelectionModel extends DefaultListSelectionModel {
    private static final long serialVersionUID = 1L;
    @Override
    public void setSelectionInterval(int index0, int index1) {
    if (enabledFlags[index0]) {
    super.setSelectionInterval(index0, index0);
    } else {
    if (getAnchorSelectionIndex() < index0) {
    for (int i = index0; i < enabledFlags.length; i++) {
    if (enabledFlags[i]) {
    super.setSelectionInterval(i, i);
    return;
    } else {
    for (int i = index0; i >= 0; i--) {
    if (enabledFlags[i]) {
    super.setSelectionInterval(i, i);
    return;

  • ListCellRenderer wont update until selected

    Hi,
    I wonder if anyone could help, I have been implementing a ListCellRenderer, and have just changed it to inherit DefaultListCellRenderer. However, either way the JList will only update when an (or any for that matter) element is selected in it. The minute you click the JList though, it updates just as it should. Here's the code
    /* Custom cell renderer for the JList */
    class MyCellRenderer extends DefaultListCellRenderer {
         public ImageIcon onlineIcn, offlineIcn;
         public MyCellRenderer() {
              setOpaque(true);
         public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
              ImageIcon onlineIcn = new ImageIcon("icons/status_online.png");
              ImageIcon offlineIcn = new ImageIcon("icons/status_offline.png");
              String s = value.toString();
              JLabel moo = new JLabel();
              contact con = (contact) value;
              moo.setText(con.getName());
              moo.setIcon(con.getStatus().equals("online") ? onlineIcn : offlineIcn);
              moo.setBackground(isSelected ? Color.lightGray : Color.white);
              moo.setForeground(con.getStatus().equals("online") ? Color.green : Color.red);
              return moo;
    }Oh and here is the JList being called:
    model = new DefaultListModel();
    list = new JList(model);
    list.setCellRenderer(new MyCellRenderer());

    Whenever you modify the data that will affect what is being displayed in the JList... call JList.repaint();
    A good way to see if you need to repaint something is to slide your component off the screen and pull it back on. If the new information is there only after sliding the component off the screen... then it just needed to be repainted.
    So... from your post... it sounds like you need to repaint your JList once you modify the data that will update the cell. Then it should look like a live update.
    -Js

  • Strange repaint behaviour with JList & Keyboard actions

    Hi everyone,
    This is my first post to the forum. You guys have been a great help in the past and I hope to contribute more in the future.
    Anyways, I've encountered some strange repainting behaviour with a JDialog that uses a JList and a JButton. The dialog is fairly straight-forward and basically this is how it works (like an open file dialog - yes I'm implementing my own filechooser of sorts):
    * JList lists a number of simple items that the user can select from.
    * Once a selection is made, an Open button (JButton) is enabled.
    * <ENTER> key is registered (using registerKeyboardAction()) with a JPanel which is used as the main content pane in the dialog.
    * The user can either click on the Open Button or hit the <ENTER> key which then closes the dialog and runs whatever logic that needs to.
    Now, the repaint problem comes in when:
    1. User selects an item.
    2. User hits the <ENTER> button
    3. Dialog closes
    4. User brings the dialog back up. This entails reloading the list by removing all elements from the list and adding new ones back in.
    5. Now... if the user uses the mouse to select an item lower in the list than what was done in step #1, the selection is made, but the JList doesn't repaint to show that the new selection was made.
    I didn't include a code sample because the dialog setup is totally straight-forward and I'm not doing anything trick (I've been doing this kind of thing for years now).
    If I remove the key registration for the <ENTER> key from the dialog, this problem NEVER happens. Has anyone seen anything like this? It's a minor problem since my workaround is to use a ListSelectionListener which manually calls repaint() on the JList inside the valueChanged() method.
    Just curious,
    Huy

    Oh, my bad. I'm actually using a JToggleButton and not a JButton, so the getRootPane().setDefaultButton() doesn't apply because it only takes JButton as an input param. I wonder why it wasn't implemented to take AbstractButton. hmmm.

  • JList wont repaint or revalidate

    Hi, I am using a JList with an AbstractListModel which contains a vector updated from a database source and a cell renderer. From another window data can be changed in the database, on the submission of the data, a retreiveData method in the listmodel updates the vector with the new data. The problem been, i want to repaint/ revalidate the list so that it re-reads the model. This works fine if i click on an item in the list. If I use repaint or anything else i get one of those nasty nullpointer exceptions.
    I think i need to call some kind of valueChanged event? I had all this working fine on tables.
    Post-grad so little experience, any help will be greatly appretiated. Thanks!

    I am using a JList with an AbstractListModelNo you aren't. "Abstract" means the class can't be created. So you are using some class that extend AbstractListModel, maybe the DefaultListModel.
    a retreiveData method in the listmodel updates the vector with the new dataThe easiest way to do this is to just create a new model. So instead of adding your updated items to a Vector, you just add them to the list model directly.
    DefaultListModel model = new DefaultListModel();
    // add items to the model
    list.setModel( model );Otherwise if you are creating a custom ListModel then you need invoke the fireContentsChanged(...) method, which will notify the JList that it need to repaint itself.

  • Problem repainting JList

    Hi everybody,
    I'm having big trouble repainting a JList after an element is inserted. So any help is mery much appreciated.
    I've a JDialog,let's say ElementListWindow with a JList, let's say ElementList , along with other components such as JComboBox, JtextArea etc. At the start up, the ElementList is populated throught "DefaultListModel" by fetching the data form database via the object ListElementDAO. Next to the ElementList i've a button which opens a modal window (also a JDialog) so that the user can add an element to the JList. The new element is inserted to the base via ListElementDAO and what i'm tryin to do is that the change is reflected to the ElementList as well. So i'm using the pattern Observer/Observable so that the ListElementDAO, which extends Observable, notifies the ElementListWindow which implements Overver and it's method "update".
    So when i insert a new element, the method "update" receives the new element. I put it in the DefaultListModel. Everything is fine until here. and try to repaint the ElementList butnothing seems to happen. The new item is not in the ElementList .
    public void update(Observable arg0, Object arg1) {
         model.insertElementAt(((Vector) arg1).get(0), 0);//model is an instance of DefaultListModel. Here, model contains the the element I just inserted to the database
         jListF.repaint();
         jListF.validate();     
    }I've printed some of the properties of ElementList .
    jListF.isValid() :true
    jListF.isVisible():true
    jListF.getParent()javax.swing.JViewport[,1,1,221x70,layout=javax.swing.ViewportLayout,alignmentX=0.0,alignmentY=0.0,
    border=,flags=25165832,maximumSize=,minimumSize=,preferredSize=,isViewSizeSet=true,
    lastPaintPosition=java.awt.Point[x=0,y=0],scrollUnderway=false]
    jListF.getPeer() instanceof LightweightPeer =true
    i've also tried
    model.add(int index,Object element) ;and also
    model.addElement(Object obj);but nothing works.
    i've also tried the "paintImmediately(...) method but no success.
    Just for information, if i try repainting a JLabel or a JTestPane inside "update" method that works perfectly but not in the case of list.
    I don't understand where the problem is.
    Please help. I'm trying to solve it for several days.

    Thanks for your replies.
    I'm sure the Vector is not empty and when i debug i see that the model contains previous elements (those already present in the list) + the one which was just inserted in the database and send to "update" method from the DAO object.
    private DefaultListModel model;
    private JList getJListF() {
         if (jListF == null) {
              model = bd_fournisseur.getListModelF();// retrieve list model form database     
              jListF = new JList(model);
              jListF.setSelectedIndex(0);
              jListF.setVisibleRowCount(4);
              jListF.setEnabled(true);
              jListF.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
         return jListF;
    }the jlistF is placed in a scrollpane. Nothing special regarding the code here.
    private JScrollPane getJScrollPane() {
         if (jScrollPane == null) {
              jScrollPane = new JScrollPane();
              jScrollPane.setBounds(new Rectangle(0, 0, 404, 66));
              jScrollPane.setBorder(null);
              jScrollPane.setViewportView(getJTextPane());
         return jScrollPane;
    }which in turn is in a JPanel.
    private JPanel getJContentPane() {
              if (jContentPane == null) {
                   jLabel7 = new JLabel();
                   jLabel7.setBounds(new Rectangle(12, 405, 61, 16));
                   jLabel7.setText("Prix TTC:");
                   jLabel6 = new JLabel();
                   jLabel6.setBounds(new Rectangle(12, 371, 72, 16));
                   jLabel6.setText("Taux TVA:");
                   jLabel5 = new JLabel();
                   jLabel5.setBounds(new Rectangle(12, 341, 53, 16));
                   jLabel5.setText("Prix HT:");
                   jLabel4 = new JLabel();
                   jLabel4.setBounds(new Rectangle(12, 311, 76, 16));
                   jLabel4.setText("Prix unitaire:");
                   jLabel3 = new JLabel();
                   jLabel3.setBounds(new Rectangle(12, 278, 56, 16));
                   jLabel3.setText("Quantité:");
                   jLabel2 = new JLabel();
                   jLabel2.setBounds(new Rectangle(12, 219, 58, 16));
                   jLabel2.setText("Libellé:");
                   jLabel1 = new JLabel();
                   jLabel1.setBounds(new Rectangle(12, 180, 64, 16));
                   jLabel1.setText("Catégorie:");
                   Fournisseur = new JLabel();
                   Fournisseur.setBounds(new Rectangle(12, 100, 75, 16));
                   Fournisseur.setText("Fournisseur:");
                   jLabel = new JLabel();
                   jLabel.setBounds(new Rectangle(12, 75, 38, 16));
                   jLabel.setText("Date:");
                   jContentPane = new JPanel();
                   jContentPane.setLayout(null);
                   jContentPane.add(getJScrollPane(), null);
                   jContentPane.add(jLabel, null);
                   jContentPane.add(getJTextFieldDate(), null);
                   jContentPane.add(Fournisseur, null);
                   jContentPane.add(getJScrollPane1(), null);
                   jContentPane.add(jLabel1, null);
                   jContentPane.add(getJComboCat(), null);
                   jContentPane.add(jLabel2, null);
                   jContentPane.add(getJScrollPane2(), null);
                   jContentPane.add(jLabel3, null);
                   jContentPane.add(getJTextFieldQuantite(), null);
                   jContentPane.add(jLabel4, null);
                   jContentPane.add(getJTextFieldPU(), null);
                   jContentPane.add(jLabel5, null);
                   jContentPane.add(getJTextFieldHT(), null);
                   jContentPane.add(jLabel6, null);
                   jContentPane.add(getJPanel(), null);
                   jContentPane.add(getJComboTaux(), null);
                   jContentPane.add(jLabel7, null);
                   jContentPane.add(getJTextFieldTTC(), null);
                   jContentPane.add(getJButton(), null);
                   jContentPane.add(getJButton1(), null);
                   jContentPane.add(getJButton2(), null);
                   jContentPane.add(getJButton3(), null);
              return jContentPane;
         }There is nothing special in my code.
    I just try to fetch the new element for DAO object and populate the list. BUT no way making it work.

  • Problem in displaying images one by one in JList

    I have a problem in displaying images one by one in Jlist. I want to show 100 images as a thumbnailview in jlist but it is talking too much time to show all the images after scalling 100 images to thumbnail view and making it into ImageIcon. So, i thought that it would be better way to show one by one after scaling it into thumnailview. But my renderer is getting calling after 100 images scaled down and setting into list. I have posted my code 2 days back but there is no reply.
    http://forum.java.sun.com/thread.jspa?threadID=789943
    I donno where i am missing in this code.
    Plz suggest me some solution for it.

    Where is the scaling done? In the ListCellRenderer? Regardless of where that is being done, I assume you are caching the scaled images after you scale them, right? If not, consider adding some sort of caching.
    This should do the trick...
    Rework your ListCellRenderer to check to see if a scaled version of the image is available. If not, start a thread to do the scaling and create an ImageIcon. In the meantime, while that thread is running, have the renderer return some sort of stock icon, like a little generic image icon. When the scaling thread completes, make a call to repaint() on the JList so the cell renderer gets re-asked for the icons. This time around, the renderer should notice that a scaled version (the ImageIcon) is available. Return that. So, this method doesn't guarantee that the images will be produced in order, 1...2...3..., but it will return images as they become available, and the overall JList rendering won't wait until all 100 are ready. If you want them returned in order, just do all of the scaling in a single thread and queue up the images to be scaled, in order.
    I hoped this helps. (If it does, please throw me some Duke Dollars.)

  • JTabbedPane lose JList contents

    Hi , this is my first question in the forum :D, i have a problem with a JTabbedPane with two tabs, each with a JList in a JPanel, the problem is that i populate the Jlists in a dynamic way using a vector. the Jlist in the first index (tab) is populated first and then I select the second tab and populate the second Jlist, but when I return to the first tab the Jlist is empty, i guess because it is repainted, which method or what i need to do to keep my JList populated !!

    In the future Swing related questions should be posted in the Swing forum.
    Without seeing your code we can only guess!
    Swing components can't be shared.
    You need to create two JLists, one for each tab.
    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|http://forum.java.sun.com/help.jspa?sec=formatting], so the posted code retains its original formatting.

  • Double buffering && repaint

    Hi there,
    I have a frame F that contains two panels P1 and P2.
    P1 uses double buffering for drawing circles and lines.
    P2 has buttons and a JList.
    When i click on a JList to have popup menu
    or when i move the frame F on the screen
    the panel P2 lost some of JList drawing.
    Actually i iconify the frame in order to oblige
    JVM to do repaint.
    How can i resolve this problem please.

    Do not ever mix heavyweight and lightweight, or else
    you won't be able to set up the correct zorder.But when i iconfiy and desiconify my frame Java
    repaint correctly.
    I need a nice tip article of how to simulate
    desiconify repainting process.
    Thabk u

  • JList(Vector) inside JScrollPane vanishes!

    Hi all, I have a problem thats driving me crazy, Im really stumped on this one;
    Im trying to update the GUI on a packet sniffer I wrote a while ago,
    I have a GUI class below as part of a larger program, this class containes a JList(Vector) inside a JScrollPane inside a JPanel inside a JFrame, I want this JList to be on the screen all the time, and grow dynamically as new elements are added to the Vector.
    Elements are added via an accessor method addPacket(Capture), you can assume the other classes in my program work fine.
    The problem is, the JFrame periodically goes blank, sometimes the scrollbars are present, sometimes not. After a while (sometimes) the JList reappears, containing the list of packets as it should, but it never lasts very long. Often it will disappear permanently.
    The class below is pretty short and simple, I really hope this is a simple and obvious mistake Ive made that someone can spot.
    Thanks,
    Soothsayer
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.io.InputStream;
    public class GUI extends JFrame
         Dimension screenResolution = Toolkit.getDefaultToolkit().getScreenSize();
         private InputStream fontStream = this.getClass().getResourceAsStream("console.ttf");
         Font outputFont;
         static final Color FIELD_COLOR = new Color(20, 20, 60);
         static final Color FONT_COLOR = new Color(150, 190, 255);
         private static JPanel superPanel = new JPanel();
         private static Vector<Capture> packetList = new Vector<Capture>(1000, 500);
         private static JList listObject = new JList(packetList);
         private static JScrollPane scrollPane = new JScrollPane(listObject);
         public GUI()
              super("LineLight v2.1 - Edd Burgess");
              this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              this.setLocation(50, 10);
              try { outputFont = Font.createFont(Font.TRUETYPE_FONT, fontStream); }
              catch(Exception e) { System.err.println("Error Loading Font:\n" + e); }
              outputFont = outputFont.deriveFont((float)10);
              listObject.setFont(outputFont);
              superPanel.setPreferredSize(new Dimension(screenResolution.width - 100, screenResolution.height - 100));
              superPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
              scrollPane.setPreferredSize(new Dimension(screenResolution.width - 100, screenResolution.height - 100));
              scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
              scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
              scrollPane.setWheelScrollingEnabled(true);
              superPanel.add(scrollPane);
              this.add(superPanel);
              this.pack();
         public void addPacket(Capture c)
              this.packetList.add(c);
              this.listObject.setListData(packetList);
              this.superPanel.repaint();
    }

    I'm having basically the same problem, And how is your code different than the example in the tutorial???
    You can also read the tutorial section on "Concurrency".
    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.
    Start your own posting if you need further help.

  • How to automatically show items in a JList

    I'm new to java and swing and I'm working with JList. I want to make the content of the list show automatically whenever a new item is added to the list model.
    The user clicks a button and a method perform some work periodically adding status message to the List model attached to the JList. All the messages appear when the method completes but I would like them to appear as it it running.
    I tried but this doesn't work:
    mList_Status.setListData(dlm.toArray());
    mList_Status.repaint();
    Is this a threading issue? Thanks!

    Is this a threading issue?Yes, you are doing all your work in the EDT, which is preventing the GUI from repainting itself. You need to use a separate Thread. Read the Swing tutorial on Concurrency for more information.

  • 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();
         }

  • Why won't my JList update?

    My JList is first dimensioned to an array with 100 elements in it but then in a function i set it to null and then I set it to a different array with a smaller amount of elements. Then i call repaint() to refresh the pane but it still doesn't change anything. The JList on my pane still shows the items in the old array. How do i fix this?

    you need to reset the listModel
    search the swing forum for
    listModel DefaultListModel
    and you'll find plenty of working examples

  • How do I get my JList selection to Display after changing

    Granted there are probably 1,000,000,000 ways to write this code. The intent is to have a list of items that are assigned into catagories and when an item is selected the catagories that the item are in are highlighted in the list. This part works OK, as I change items the catagories change to reflect the current item catagories. I have two buttons to add catagories to items and remove catagories from items. The catagory to add is selected from a JCombo drop down list and then the user clicks the addcat button to add the catagory to the item.
    My problem is that the catagories in the JList (that also reside in a JScrollPane) do not show as selected after the list is updated. If I click the addcat button twice then the new catagory is highlighted. I thought that the suggestion in other forum messages to add revalidate and repaint would work so I tried that both at the list and the scrollpane level with no effect.
    -------------- Button Listener code --------------------
    addcat.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    // get the curent catagory from the JCombo..
         String selectedcat = (String) fullcatlist.getSelectedItem();
    // get the curent Item from the JCombo..
         String selecteditem = (String) itemlist.getSelectedItem();
    // add item to catagory
         items.addItemCatagory(selecteditem,selectedcat);
    // debug
         product.setText(selectedcat +"::"+selecteditem);          
         int cnt = 0;
    // get a list of all catagories for this item
         String[] tgtList = catagories.getItemCatagories(selecteditem);
         // debug
         product.setText(selectedcat);          
    // get the JList list
         final ListModel lm = catlist.getModel();
    // get the list size
         int lsize = lm.getSize();
         String st ="";
         for (int j = 0; j < lsize;j++) {
    // get jth element of the list
         st = (String)lm.getElementAt(j);
    // compare it to the selected catagories list in if a match
    // set the index into the selected index array
         for (int k=0;k<tgtList.length;k++) {
         if ( st.compareTo(tgtList[k]) == 0 )
         lst[cnt++]=j;          
    //set up the selections
         int[] ilst = new int[cnt];
         for (int k = 0; k<cnt;k++)
         ilst[k] = lst[k];
    // enable teh selected indice
         catlist.setSelectedIndices(ilst);
    // paint the frame
         scrollPane.revalidate();
         scrollPane.repaint();
    --------------------- end code -----------------

    This might sound sarcastic, but it's not:
    I have no clue how to fix your code, but if your bored and want to try something, try copy-and-pasting that section right afterwards. You'd probably need to change some variables, but, again, I have no clue. This is all just a wild guess. Sorry I couldn't help you any more.

  • Cant delete or add item to Jlist as nthing happens

    Hi all,
    regarding the first part where pass of string array into object array. I have done it (thanks again for the help). But regarding the add and remove elements from the Jlist cant be done.. below is my code for the delete button when press. I cast it into int for the ManualList.getSelectedIndex();(at part A) but cant display and keep having a error call
    java.lang.NullPointerException at ManualChange&ValueReporter.valueChanged
    code for value reporter is at part B
    Part A
    private void deleteMouseClicked(MouseEvent e)
    int n =(int)ManualList.getSelectedIndex();
    if (!(n < 0) || (n > listModel.size()))
    listModel.remove(n);
    delete.setEnabled(false);
    ManualList.repaint();
    ManualList.revalidate();
    Part B
    private class ValueReporter implements ListSelectionListener {
    public void valueChanged(ListSelectionEvent event) {
    // if (!event.getValueIsAdjusting())
    // gettext.setText(ManualList.getSelectedValue().toString());
    ManualList.repaint();
    ManualList.revalidate();
    Any help is greatly appreciated.
    alright, i redo part A the code is shown below but i still cant get the display out.
    Is there some problem in my code? or is the repaint and revalidate thing wrong usage here ? Need help regarding this. Thanks
    int n =ManualList.getSelectedIndex();
    if (!(n < 0) || (n > listModel.size()))
    listModel.removeElement(arrayObject[n]);
    delete.setEnabled(false);
    ManualList.repaint();
    ManualList.revalidate();

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import java.awt.event.MouseEvent.*;
    import javax.swing.event.*;
    import java.io.*;
    import javax.swing.DefaultListModel.*;
    import java.util.Properties;
    import java.util.ArrayList;
        public class smallProgram extends JFrame //implements ListSelectionListener
            JPanel p;
        private DefaultListModel listModel;
         JLabel ManualJob = new JLabel();
         JTextField gettext  = new JTextField();
         JScrollPane scrollPane1 = new JScrollPane();
         JButton okButton = new JButton();
         JButton cancelButton = new JButton();
         JButton add = new JButton();
         JButton delete = new JButton();
         JList ManualList;
         int tokenNo;
         String real,ss;
         String[] values;
         Object[] arrayObject;
         java.util.StringTokenizer tokenizer;
         BufferedReader in;
         ArrayList data;
         public static void main(String args[])
             new smallProgram();
          public smallProgram()
                setTitle("Small Program");
                p = (JPanel) this.getContentPane();
                p.setLayout(null);
                setSize(515, 585);
                setVisible(true);
               //---- ManualJob ----
               ManualJob.setText("Manual Jobs Classification");
               ManualJob.setFont(new Font("Times New Roman", Font.BOLD, 14));
               p.add(ManualJob);
               ManualJob.setBounds(10, 435, 190, 35);
               setVisible(true);
               //---- gettext ----
               gettext.setFont(new Font("Times New Roman", Font.PLAIN, 12));
               p.add(gettext);
               gettext.setBounds(365, 435, 115, 25);
               setVisible(true);
               //Buttons for add, del, ok and cancel
               //---- Add ----
               add.setText("Add");
               add.addMouseListener(new MouseAdapter() {
                   @Override
                   public void mouseClicked(MouseEvent e) {
                       addMouseClicked(e);
               p.add(add);
               add.setBounds(355, 485, 60, add.getPreferredSize().height);
              //---- delete ----
               delete.setText("Delete");
               delete.addMouseListener(new MouseAdapter() {
                   @Override
                   public void mouseClicked(MouseEvent e) {
                       deleteMouseClicked(e);
               p.add(delete);
               delete.setBounds(new Rectangle(new Point(430, 485), delete.getPreferredSize()));
               //---- okButton ----
               okButton.setText("OK");
               okButton.addMouseListener(new MouseAdapter() {
                   @Override
                   public void mouseClicked(MouseEvent e) {
                       okButtonMouseClicked(e);
               p.add(okButton);
               okButton.setBounds(335, 520, 75, okButton.getPreferredSize().height);
               //---- cancelButton ----
               cancelButton.setText("Cancel");
               cancelButton.addMouseListener(new MouseAdapter() {
                   @Override
                   public void mouseClicked(MouseEvent e) {
                       cancelButtonMouseClicked(e);
               p.add(cancelButton);
               cancelButton.setBounds(420, 520, 75, cancelButton.getPreferredSize().height);
               ss = ("test1,test2,test3,test4,test5"); //My string ss
               int length = ss.length();
               int asd = (ss.indexOf('_'))+1;
               real = ss.substring(asd, length);
               tokenizer = new java.util.StringTokenizer(real,",");
               tokenNo = tokenizer.countTokens();
               data = new ArrayList();
               values = new String [tokenNo];
    //           Object[] arrayObject = data.toArray();// this is my initial code where arraylist is pass to object
                   for(int i =0; i< tokenNo; i++)   // pass string-ss into arraylist individually
                    data.add((tokenizer.nextToken(",")));
                    //values[i] = tokenizer.nextToken(",");
                    data.trimToSize();
                    //System.out.println("tokenizer"  + values);
    int aaaa = data.size();
    System.out.println("size " + aaaa);
    System.out.println("tokenizer" + tokenNo);
    System.out.println("arraylist "+ i + data.get(i));
    //JLIST
    //======== scrollPane1 ========
    //---- ManualList ---- This is my Jlist // copy arraylist into Object[] then pass it into JList
    listModel = new DefaultListModel();
    /* listModel = new DefaultListModel(); Part A also continue from above
    * for (int i = 0; i< arrayObject.length;i ++)
    * listModel.addElement(objectArray[i].toString());
    * JList ManualList = new JList(listModel); //tried using listModel.method() to remove item in Jlist but return nullException
    arrayObject = data.toArray();
    JList ManualList=new JList(arrayObject);
    ManualList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    ManualList.setSelectedIndex(0);
    ManualList.setVisibleRowCount(5);
    ManualList.setFont(new Font("Times New Roman", Font.PLAIN,12));
    ManualList.setBorder(new MatteBorder(1, 1, 1, 1,Color.black));
    ManualList.setLayoutOrientation(JList.VERTICAL_WRAP);
    values = new String[tokenNo];
    ManualList.addListSelectionListener(new ValueReporter());
    // JScrollPane listPanel = new JScrollPane(ManualList);
    scrollPane1.setViewportView(ManualList);
    p.add(scrollPane1);
    scrollPane1.setBounds(210, 435, 130, 75);
    setVisible(true);
    { // compute preferred size
    Dimension preferredSize = new Dimension();
    for(int i = 0; i < p.getComponentCount(); i++) {
    Rectangle bounds = p.getComponent(i).getBounds();
    preferredSize.width = Math.max(bounds.x + bounds.width,preferredSize.width);
    preferredSize.height = Math.max(bounds.y +bounds.height, preferredSize.height);
    Insets insets = p.getInsets();
    preferredSize.width += insets.right;
    preferredSize.height += insets.bottom;
    p.setMinimumSize(preferredSize);
    p.setPreferredSize(preferredSize);
    private void addMouseClicked(MouseEvent e)
    private void deleteMouseClicked(MouseEvent e) //nthing happen here
    int n =ManualList.getSelectedIndex();
    if (!(n < 0) || (n > listModel.size()))
    listModel.removeElement(arrayObject[n]);
    delete.setEnabled(false);
    ManualList.repaint();
    ManualList.revalidate();
    /* int n =ManualList.getSelectedIndex(); //tried using this but failed
    if (!(n < 0) || (n > listModel.size()))
    listModel.remove(n);
    delete.setEnabled(false);
    ManualList.repaint();
    ManualList.revalidate();
    private void okButtonMouseClicked(MouseEvent e) {
    private void cancelButtonMouseClicked(MouseEvent e) {
    private class ValueReporter implements ListSelectionListener {
    public void valueChanged(ListSelectionEvent event) {
    // if (!event.getValueIsAdjusting())
    // gettext.setText(ManualList.getSelectedValue().toString());
    //String name=(String) ManualList.getSelectedValue();
    //System.out.println(name);
    private void ManualListMouseClicked(MouseEvent e) {
    // int n = (int)ManualList.getSelectedIndex();
    // if (!(n < 0) || (n > listModel.size()))
    // delete.setEnabled(true);
    ok this is a small complete program
    Thanks for the time to read this

Maybe you are looking for

  • HT4527 how do I move my itunes on an external drive to a new laptop?

    HELP!! My Itunes has been on an external (seagate) but the laptop that I've been using to access this is on it's last legs. I purchased a new Windows 7 laptop with a faster processer & lots of memory & storage. The itunes has been backed up on the dr

  • ES2 best practice for how much stuff should be in one application?

    I'm wondering if there is a best practice/recommended amount of the maximum amount of forms/processes/etc that you should have contained within one application in ES2?  I have an application which has about 5 processes, and has over 300 xdp forms.  W

  • Command line to clear cache?

    JRE 1.4.2_04 I need to clear the cache on about 2000 machines and would prefer not to visit each one physically. Is there a command line parameter I can feed to jpicpl32.exe to trigger the cache clear? I've seen several threads asking about this but

  • Wrong behavior doing customize of Partner Schema in EBP

    Dear supporters, We work with SRM server 550 SP 14. We want to define partner function" Invoicing Party" in Partner Schema,  and map to purchase order transaction. We are trying to define Partner Schema under Partner Determination Procedure, but we a

  • Guest WiFi not working with DHCP disable

    Hello, I am using my "server" for handling DHCP requests, in the past i used my router to perform this task. After disabling my DHCP server on the router i found out my guest WiFi is not working anymore. It seems it keeps searching for a DHCP server