AWT List or JList ?

Hi everybody,
I am using javax.swing for my layout (buttons, textfields,..) but when I try to use JList and add some text to it (lstLog("hi");) I get this error:
symbol : method add(java.lang.String)
location: class javax.swing.JList
lstLog.add("hi");
1 error
BUILD FAILED (total time: 0 seconds)
But I don't get this error if I use another List from AWT, can u explain this to me pleas ? thank you!

Rkas wrote:
why not??Concrete answer: because it just doesn't exist, simple as that. Go to the JList API which you can find here and try to find a method called add(...). You won't find it because JList doesn't have this. It does however inherit an unrelated method of the same name from container (see below).
Theoretical answer: Swing handles things differently than AWT. With Swing all components have a non-GUI model which handle the logic of the component, and for JList that logic is maintaining the data list itself. So the GUI portion of JList doesn't worry about what data it holds, but its model, which usually is a DefaultListModel does worry about this information and can change the information with the appropriate method calls.
when I insert JList lstLog. in netbeans I get all the methodes of this component!! Yes, and I'm sure that it will display an "add" method, but understand that this method derives from Container (I wonder if NetBeans displays this information), and so has absolutely nothing to do with adding or removing items from a list.
so what do u mean by "JList doesn't" ??JList itself doesn't. Again, see the API.

Similar Messages

  • Some problems in "AWT.List', Pls help !

    Dear all,
    Now i am studying a 'AWT.List'. I would like to know that how can i auto-swap the content on the 'AWT.List' into 2 or 3 line if the length of content is longer than the width of 'AWT.List'. And if it can be implemented, what is the return value of the specific rows ?
    Lung,
    Thx !

    As far as I know, List doesn't allow you to do that kind of thing. However, it could be pretty easily done with a JList and a JTextArea as ListCellRenderer.

  • Display image in java.awt.List

    hello guys,
    How i can display image in java.awt.List means listbox. give me sample code. if you have
    Waiting for your favorable reply.
    Regards,
    Bhavesh Kharwa

    java.awt.List you can not.
    javax.swing.JLast you can.

  • Problem with Horizontal Scroll on java.awt.List

    I use the same code for a General Application as a CDC Application.
    I have no problem at all with the General Application but on the CDC I can't scroll to the right (horizontal).
    Why do I get this problem on the CDC application and not on a regular application?
    I use the PP-1.0 Profile for the CDC application. Does it not support horizontal scroll on java.awt.List?
    This is the code:
    * Main.java
    * Created on den 22 augusti 2007, 10:52
    package cdcapplication6;
    * @author  Erik Rothman
    public class Main extends java.awt.Frame {
        /** Creates new form Main */
        public Main() {
            initComponents();
              for (int i = 0; i < 10; i++) {
                   list1.add("Short text");
                   list1.add("Some very long text indeed. Some very long text indeed.");
        /** 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.
        // <editor-fold defaultstate="collapsed" desc=" Generated Code ">                         
        private void initComponents() {
            list1 = new java.awt.List();
            addWindowListener(new java.awt.event.WindowAdapter() {
                public void windowClosing(java.awt.event.WindowEvent evt) {
                    exitForm(evt);
            add(list1, java.awt.BorderLayout.CENTER);
            pack();
        }// </editor-fold>                       
        /** Exit the Application */
        private void exitForm(java.awt.event.WindowEvent evt) {                         
            System.exit(0);
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new Main().setVisible(true);
        // Variables declaration - do not modify                    
        private java.awt.List list1;
        // End of variables declaration                  
    }

    I use the same code for a General Application as a CDC Application.
    I have no problem at all with the General Application but on the CDC I can't scroll to the right (horizontal).
    Why do I get this problem on the CDC application and not on a regular application?
    I use the PP-1.0 Profile for the CDC application. Does it not support horizontal scroll on java.awt.List?
    This is the code:
    * Main.java
    * Created on den 22 augusti 2007, 10:52
    package cdcapplication6;
    * @author  Erik Rothman
    public class Main extends java.awt.Frame {
        /** Creates new form Main */
        public Main() {
            initComponents();
              for (int i = 0; i < 10; i++) {
                   list1.add("Short text");
                   list1.add("Some very long text indeed. Some very long text indeed.");
        /** 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.
        // <editor-fold defaultstate="collapsed" desc=" Generated Code ">                         
        private void initComponents() {
            list1 = new java.awt.List();
            addWindowListener(new java.awt.event.WindowAdapter() {
                public void windowClosing(java.awt.event.WindowEvent evt) {
                    exitForm(evt);
            add(list1, java.awt.BorderLayout.CENTER);
            pack();
        }// </editor-fold>                       
        /** Exit the Application */
        private void exitForm(java.awt.event.WindowEvent evt) {                         
            System.exit(0);
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new Main().setVisible(true);
        // Variables declaration - do not modify                    
        private java.awt.List list1;
        // End of variables declaration                  
    }

  • Awt.List Flicker when adding many items.

    I need to add a lot of items to an awt.List (around 100),
    is there a way to do this off-screen so that it wont flicker
    like crazy while I'm adding the items in a loop?
    Thanks,
    Rob.

    you can make your list invisible setVisible(false) when it performed the adding make it visible.You can use Thread.sleep() to stay for a while till adding has not been done!
    hope it will match with ur requirements

  • Problem In Awt List

    I am Having problem with Awt List component
    setSize
    setPrefferedSize
    setMaximumSize
    None is working I have limited screen are to use in applet Hence I want to limit the width of List
    Below Is My code I am using in Devloping Some Applet.
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.Frame;
    import java.awt.List;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    public class ListSizeProblem extends Frame {
         public List list1;
         ListSizeProblem (String t) {
              this.setTitle(t); // setting up the main window
              this.setSize(500, 400);
              this.setLocation(50, 50);
              this.setLayout(new BorderLayout());
              addWindowListener(new WindowAdapter() { // application will exit if window is closed
                 public void windowClosing(WindowEvent e) {
                      System.exit(0);
              list1 = new List(15, false);
              //list1.setSize(new Dimension(40,200));
              list1.setPreferredSize(new Dimension(40,200));
              //list1.setMaximumSize(new Dimension(40,200));
               for (int i = 1; i < 21; i++) {
                 list1.add("But"+i);
              this.add(list1,BorderLayout.WEST);
              this.pack();
              this.setVisible(true);
         public static void main (String [] args) {
              ListSizeProblem mainframe = new ListSizeProblem("List Size");
    }can somebody help me

    It is indeed a bug. Once your List has data in it, the getPreferredSize method starts calling preferredSize(int rows) method. This method in turn asks the list's peer for the size. The result is that the preferred size you set is completely ignored (hence a bug). Quick fix would be to override the getPreferredSize method like so.
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.Frame;
    import java.awt.List;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    public class ListSizeProblem extends Frame {
        public List list1;
        ListSizeProblem(String t) {
            this.setTitle(t); // setting up the main window
            this.setSize(500, 400);
            this.setLocation(50, 50);
            this.setLayout(new BorderLayout());
            addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
            list1 = new List(15, false) {
                Dimension size = new Dimension(40, 200);
                public java.awt.Dimension getPreferredSize() {
                    return size;
            for (int i = 1; i < 21; i++) {
                list1.add("But" + i);
            this.add(list1, BorderLayout.WEST);
            this.setVisible(true);
        public static void main(String[] args) {
            ListSizeProblem mainframe = new ListSizeProblem("List Size");
    }The list is not 200 pixels high, but this just comes from the fact that you don't have a BorderLayout.NORTH or BorderLayout.SOUTH object yet, so the BorderLayout is alowed to extend the height of the list.
    And you seem to havea pretty exact idea on the size you want your components to be. If the frame is not going to be resizable, then you can use no layout manager if you want. This would require you to set the exact bounds of every component you add to the frame.

  • Removing scrollbar from AWT List

    Hi,
    I have an instance of List on my screen. I noticed when I have more than one item on the list, it shows automatically a vertical and horizontal scrollbars.
    I have to disable scrollbars, but cannot find out if it is possible with AWT List or should I opt for a different Component than List.
    Could anyone give me a hand?
    Thank you,
    Caren

    List is what you want. Use this constructor...List(int, boolean). First argument is number of items to display in the list, second is if List is mulitle selection list. So for a normal list with 5 items do this:
    List myList = new List5, false);
    This should stop a scrollbar being put in (unless you add more than 5 items). If this doesn't work it's proably your layout manager set up.
    Hope this helps

  • How to append the data list bod (JList)

    how to append the data list box (JList)
    Message was edited by:
    raju_2reddy

    For this you will need a nested internal table. such that each column of the internal table should be declared as another internal table.
    Try something like this :
    " Lets say that the type of table that will be returned by the function BOM is ty_ret_tab, then declare as follows
    types begin of ty_tab,
    c1 type table of ty_ret_tab,
    c2 type table of ty_ret_tab,
    end of ty_tab.
    data gt_tab type standard table of ty_tab,
            gwa_tab like ty_tab.
    Now the question is how many columns should you declare ? Because you said that in a loop you intend to call a function which will return a internal table and this internal table you need to store in a column of another internal table. And if this is not fixed, you would need to do some dynamic programming to achieve this.
    But if we assume that there are fixed number of columns and fixed number of loops, then within the loop, you wiill have to simply move the data from the returned table to each of the columns. Then append the work area outside the loop.
    data field(30) type c.
    data c_tabix(10) type c.
    field-symbols <fs> type ret_tab.  " this should be
    Loop at itab.
    call function BOM...
    exporting...
    importing.....
    tables  ret_itab.
    c_tabix = sy-tabix.
    concatenate 'C' c_tabix into field.
    condense field.
    assign component  (field) of structure gwa_tab to <fs>.
    <fs> = ret_tab.   " Pass data to each column
    endloop.
    append gwa_tab to gt_tab.  " Now a single record with all columns containing an internal table is built.
    Hope this pseudo code helps.
    BR,
    Advait

  • Scrollbars and awt.List

    Hello,
    I'm a first year student form the Netherlands in software design. And as of this semester I'm getting Java (finally a new language to learn!). Everything has gone very smoothly, I was hoping of more of a challenge trying to learn it, but it goes very easily (maybe I shouldn't have programmed in C++ for 3 years :P).
    Though now I'm having a slight problem with my code. v _ v '
    My project has to be competly in awt widget's, and I thought I'd do something more than required (it would seem that my teachers expect me to ^ _ ^).
    In this list I'm required to use a fixed width font to "simulate" 2 panels (almost similar to the TableList in Swing) with a pipe ( | ) character as a line. It means that I need to cut off words that cross the boundry.
    The above (and the rest of the assignment) works perfectly (and I've done the actual required part in less than 30 minutes), but now I've come to want to add tool tips to all the elements.
    I've made a tooltip class (it works btw), but I need to get the item in the list my mouse is hovering over.
    I believe a row is 20 pixels high (or something like that), so I divide the y value (of the local mouse position) by 20 and use the integer part as the index.
    And here comes the problem.
    When the list scrolls then the method I described above won't work anymore.
    I think that my method is (atleast) similar as to what other programs do, save that it adds the scroll info as well.
    Now here's my real problem. I can't (or don't know how) to get the scrollbar info from the list. I know there's a handy function is Swing, but I'm only allowed to use awt.
    I've also read that the scrollbars are part of the peer's (native to the OS) so I can't access them.
    So my true question is, what (if any) event should I listen to, to get scroll movements (not mouse wheel scrolling)?
    And if there isn't any way to listen to the events, then do you have any idea how to tackle this problem?
    Thank you for your time,
    MLeoDaalder

    Showing me your misbehaving output is not helpful.
    I have successfully implemented what you are attempting, using Swing which I understand you cannot use but it should work the same way using AWT.
    My main class extends JFrame (you would extend Frame) and implements MouseMotionListener. The mouseMoved(MouseEvent evt) method in the main class updates the tool tip, based on the evt.getX() and evt.getY().
    I have a class (call it LCanvas) that extends JPanel (you would extend Panel) . The class adds a MouseMotionListener and has a paint(Graphics g) method that records the borders of each line that gets painted by g.drawString(String s, int x, int y). (Some of the painted lines may be outside of the displayed area.)
    When I construct LCanvas, I pass it the JFrame (you would use Frame) of the main class. So my contructor looks like:
    public LCanvas(JFrame f) {
    addMouseMotionListener((MouseMotionListener) f);
    Back in main(String [ ] args), I set up my scrollable window as:
    MainClass f = new MainClass();
    LCanvas lc = new LCanvas(f);
    JScrollPane sp = new JScrollPane(lc);
    content_pane.add(sp);
    I don't know how you are trying to implement this but you should be able to compare it to my implementation that works and, since you are such a clever guy, figure out what's going wrong.

  • Horizontal scroll bar in AWT List

    I need to shrink the width of my list by putting a horizontal scroll bar. Does anyone know how to add one onto my list component

    The code looks like this. I can really use some help here.
    Label grp = new Label("Group By:");
         buildConstraints(constraints, 0, 2, 1, 1, 1, 1);
         gridbag.setConstraints(grp, constraints);
         add(grp);
         grplist = new List(4, false);
    buildConstraints(constraints, 1, 2, 1, 1, 1, 1);
         gridbag.setConstraints(grplist, constraints);
         for(i = 0; i <= number_of_fields; i++){
              grplist.add(data[0]);
    add(grplist);
         data6 = new Checkbox("6 sigma data",false);
         buildConstraints(constraints, 1, 12, 1, 1, 1, 1);
         gridbag.setConstraints(data6, constraints);
         add(data6);
         show = new Checkbox("Show values",false);
         buildConstraints(constraints, 1, 13, 1, 1, 1, 1);
         gridbag.setConstraints(show, constraints);
         add(show);
         aver = new Checkbox("Plot Average",false);
         buildConstraints(constraints, 1, 14, 1, 1, 1, 1);
         gridbag.setConstraints(aver, constraints);
         add(aver);
         remove(aver);

  • Panic! Possible to change Fontcolor in List in AWT?

    I really need to know if it is possible to change the font color in AWT for different list entries in th awt.List object.
    I managed to change the fonts with no problem, but the font color...
    I�m using my list as an own object which extends the panel. Is this the right way to do it or?
    If anyone has any hints or a piece of sample code (if it is possible) please let me know.
    //Peter
    //To call the Lists class from outside
    private void setupTheList()
    String[] str = {"2","4","","","","","","","","","","","","","","","","",""}; //Items to be added to the List.
    int[] sel = {1,4,7,8,9,13}; //Which are to be selected in the List
    li = new Lists(str,5,sel);
    class Lists extends Panel{
    List list;
    public void paint(Graphics g)
    Graphics g2;
    g2 = list.getGraphics();
    g2.setColor(Color.red);
    public Lists(String[] listItems, int listLength, int[] listItemSelected){
    list = new List(listLength,true);
    for(int i = 0; i < listItems.length; i++){
    list.add(new String(listItems));
    for(int j = 0; j < listItemSelected.length; j++){
    list.select(listItemSelected[j]);
    GridBagLayout gbl = new GridBagLayout();
    setLayout(gbl);
    add(list);

    Of course create your own list you need a scrollbar, canvas or panel, and implements Mouselistener, and ItemListener after that you draw what Color, image or text you want.

  • List updates accumulating loops,index 0 selected

    Hi, I have tried several day solve this.
    ListCellRenderer and ListSelectionListener with list of four male names.
    If you select JUST THE FIRST NAME in the list and press "Change gender" button, the System.print.out shows unnecessarily repeating loops when updating list (=slow down).
    How to avoid extra loops when first name is selected?
    Thanks!
    TestCase.java
    import java.awt.*;
    import java.util.*;
    import java.io.*;
    import javax.swing.*;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    public class TestCase {
         boolean packFrame = false;
      public TestCase() {
         TestCaseFrame frame = new TestCaseFrame();
        if (packFrame) {
          frame.pack();
        else {
          frame.validate();
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        Dimension frameSize = frame.getSize();
        if (frameSize.height > screenSize.height) {
          frameSize.height = screenSize.height*9/10;
        if (frameSize.width > screenSize.width) {
          frameSize.width = screenSize.width*9/10;
        frame.setLocation(10,10);
        frame.setVisible(true);
      public static void main(String[] args) {
        try {
          UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
        catch(Exception e) {
          e.printStackTrace();
        new TestCase();
    TestCaseFrame.java
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.util.*;
    import java.io.*;
    import javax.swing.*;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    public class TestCaseFrame extends JFrame {
      MyCellRenderer myCellRenderer = new MyCellRenderer();
      BorderLayout borderLayout = new BorderLayout();
      Container contentPane;         
      JPanel panel = new JPanel();
      DefaultListModel defaultListModel = new DefaultListModel();
      JList list = new JList(defaultListModel); 
      JScrollPane scrollPane = new JScrollPane(list);
      ListSelectionModel listSelectionModel;
      JLabel label = new JLabel("<html>Select THE FIRST name and press button! <br>Check System.out.print");
      JButton button_changeGender = new JButton("Change gender");  
      boolean genderNow_male = true;
      String[] names = new String[4];
      public TestCaseFrame() {
           enableEvents(AWTEvent.WINDOW_EVENT_MASK);
        try {
          jbInit();
          this.pack();
        catch(Exception e) {
          e.printStackTrace();
      private void jbInit() throws Exception  {
        contentPane = (Container) this.getContentPane();  
        contentPane.setLayout(borderLayout);
        this.setDefaultCloseOperation(3);
        panel.add(label, null);  
        panel.add(scrollPane, null);  
        panel.add(button_changeGender , null);
        button_changeGender.addActionListener(new button_changeGender_actionAdapter(this));
        button_changeGender.setVisible(true);
        button_changeGender.setEnabled(true);
        contentPane.add(panel);
        // default values, gender is now male
        names[0] = "Bill";
         names[1] = "James";
         names[2] = "Martin";
         names[3] = "Peter";
            for (int counter = 0 ; counter < names.length; counter++) {
             defaultListModel.addElement(names[counter]);
        listSelectionModel = list.getSelectionModel(); 
        listSelectionModel.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);  
        listSelectionModel.addListSelectionListener(
                new SharedListSelectionHandler(this));   
        list.setSelectedIndex(0);
        list.setVisibleRowCount(7);
        list.setCellRenderer(myCellRenderer);
      void ChangeGender() {    // changes the gender of names in the list if the button was pressed
           System.out.println("\nEntering method ChangeGender");
             defaultListModel.removeAllElements();
                if  (genderNow_male) {
                     genderNow_male = false;
                     names[0] = "Doris";
                     names[1] = "Helen";
                     names[2] = "Nicole";
                     names[3] = "Susan";
                } else {
                     genderNow_male = true;
                     names[0] = "Bill";
                     names[1] = "James";
                     names[2] = "Martin";
                     names[3] = "Peter";
                 for (int counter = 0 ; counter < names.length; counter++) {
                      System.out.println("ChengeGender method (name, index): " + names[counter] + ", " + counter);
                           defaultListModel.addElement(names[counter]);
            list.ensureIndexIsVisible(0);           
            System.out.println("Quitting method ChangeGender\n");          
      void button_changeGender_actionPerformed(ActionEvent e) {
                ChangeGender();
    class button_changeGender_actionAdapter implements java.awt.event.ActionListener {
         TestCaseFrame adaptee;   
         button_changeGender_actionAdapter(TestCaseFrame adaptee) {  // LL1010 oli DelNodesGameFrame adaptee
        this.adaptee = adaptee;
      public void actionPerformed(ActionEvent e) {
        adaptee.button_changeGender_actionPerformed(e);
    class MyCellRenderer extends Container implements ListCellRenderer {      // oli JPanelin tilalla JLabel
         private static final Color HIGHLIGHT_COLOR = new Color(0, 0, 128);
         private JTextArea textarea;  
         private JPanel cell_panel = new JPanel();
         public MyCellRenderer() {
               textarea = new JTextArea("abcTesting_");
               textarea.setOpaque(true);                      
           public Component getListCellRendererComponent(final JList list,
                    final Object value, final int index, final boolean isSelected,
                    final boolean cellHasFocus) {
                String entry = (String) value;            
                System.out.print("Cell renderer (name, index): " + entry + ", " + index);
                textarea.setText(entry);
                textarea.setColumns(20);
                if(isSelected){
                     System.out.print("   - is selected");
                     textarea.setBackground(list.getSelectionBackground());
                     textarea.setForeground(list.getSelectionForeground());
                } else{
                     System.out.print("   - not selected");
                     textarea.setBackground(list.getBackground());
                     textarea.setForeground(list.getForeground());
                System.out.print("\n");
                setEnabled(list.isEnabled());
                setFont(list.getFont());
                cell_panel.removeAll();
                cell_panel.setOpaque(true);
                cell_panel.setLayout( new FlowLayout(FlowLayout.LEFT));
                cell_panel.add(textarea);  // BorderLayout.WEST,   label_linkTitle
                return cell_panel;           
    class SharedListSelectionHandler implements ListSelectionListener {
         TestCaseFrame adaptee;
         SharedListSelectionHandler(TestCaseFrame adaptee) { 
                  this.adaptee = adaptee;
         public void valueChanged(ListSelectionEvent e) {                 
         ListSelectionModel lsm = (ListSelectionModel)e.getSource();  
         if( !(lsm.isSelectionEmpty()) && !e.getValueIsAdjusting() ) {
                   System.out.print("\nCurrently selected list indexes: ");
                        for (int i = lsm.getMinSelectionIndex(); i <= lsm.getMaxSelectionIndex(); i++) { 
                             if (lsm.isSelectedIndex(i)) {
                                  System.out.print(i + " ");                                                  
                   System.out.print("\n");
    }

    I think you are spending too much time worrying about how Swing does things and not enough time on reducing the complexity of your renderer. You seem to have far too much going on in the body of the renderer.
    Maybe something like
    class MyCellRenderer implements ListCellRenderer
    {      // oli JPanelin tilalla JLabel
        private static final Color HIGHLIGHT_COLOR = new Color(0, 0, 128);
        private JTextArea textarea;
        private JPanel cell_panel = new JPanel();
        public MyCellRenderer()
            textarea = new JTextArea("abcTesting_");
            textarea.setColumns(20);
            textarea.setOpaque(true);
            cell_panel.removeAll();
            cell_panel.setOpaque(true);
            cell_panel.setLayout(new FlowLayout(FlowLayout.LEFT));
            cell_panel.add(textarea);  // BorderLayout.WEST,   label_linkTitle
        public Component getListCellRendererComponent(final JList list,
                final Object value, final int index, final boolean isSelected,
                final boolean cellHasFocus)
            String entry = (String) value;
            textarea.setText(entry);
            if (isSelected)
                textarea.setBackground(list.getSelectionBackground());
                textarea.setForeground(list.getSelectionForeground());
            } else
                textarea.setBackground(list.getBackground());
                textarea.setForeground(list.getForeground());
            textarea.setEnabled(list.isEnabled());
            textarea.setFont(list.getFont());
            return cell_panel;
    }Edited by: sabre150 on May 23, 2009 11:54 AM

  • 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 can I keep the selectedIndex of two JLists the same?

    I have two independant JLists. I have one button to add items from two textfields to the lists. I also have one button to remove the selected items from the lists. However because the items in both JLists are related I want to make sure the selected index of one is always equal to the selected index of the other. HOW!

    OK, so here is the current code, there must be an easy way to do it, Swing gurus please help.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    public class ListDemo extends JFrame
                          implements ListSelectionListener {
        private JList list;
        private JList list2;
        private DefaultListModel listModel;
        private DefaultListModel listModel2;
        private static final String hireString = "Add";
        private static final String fireString = "Remove";
        private JButton fireButton;
        private JTextField employeeName;
        private JTextField percent;
        private JSlider per;
        public ListDemo() {
            super("ListDemo");
            listModel = new DefaultListModel();
            listModel.addElement("Alison Huml");
            listModel.addElement("Kathy Walrath");
            listModel.addElement("Lisa Friendly");
            listModel.addElement("Mary Campione");
            listModel2 = new DefaultListModel();
            listModel2.addElement("100");
            listModel2.addElement("80");
            listModel2.addElement("50");
            listModel2.addElement("10");
            //Create the list and put it in a scroll pane
            list = new JList(listModel);
            list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            list.setSelectedIndex(0);
            list.addListSelectionListener(this);
            JScrollPane listScrollPane = new JScrollPane(list);
            //Create the percentlist and put it in a scroll pane
            list2 = new JList(listModel2);
            list2.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            list2.setSelectedIndex(0);
            list2.addListSelectionListener(this);
            JScrollPane listScrollPane2 = new JScrollPane(list2);
            JButton hireButton = new JButton(hireString);
            hireButton.setActionCommand(hireString);
            hireButton.addActionListener(new HireListener());
            fireButton = new JButton(fireString);
            fireButton.setActionCommand(fireString);
            fireButton.addActionListener(new FireListener());
            employeeName = new JTextField(10);
            employeeName.addActionListener(new HireListener());
            String name = listModel.getElementAt(
                                  list.getSelectedIndex()).toString();
            employeeName.setText(name);
            per = new JSlider(JSlider.HORIZONTAL, 0, 100, 50);
            per.setMajorTickSpacing(10);
            per.setPaintTicks(true);
            per.setPaintLabels(true);
            percent = new TextField(10);
            percent.setValue(new Integer(1));
            percent.addActionListener(new HireListener());
            String name2 = listModel2.getElementAt(
                                  list2.getSelectedIndex()).toString();
            percent.setText(name2);
            //Create a panel that uses FlowLayout (the default).
            JPanel buttonPane = new JPanel();
            buttonPane.add(employeeName);
            buttonPane.add(per);
            buttonPane.add(hireButton);
            buttonPane.add(fireButton);
            Container contentPane = getContentPane();
            contentPane.add(listScrollPane, BorderLayout.CENTER);
            contentPane.add(listScrollPane2, BorderLayout.EAST);
            contentPane.add(buttonPane, BorderLayout.SOUTH);
        class FireListener implements ActionListener {
            public void actionPerformed(ActionEvent e) {
                //This method can be called only if
                //there's a valid selection
                //so go ahead and remove whatever's selected.
                int index = list.getSelectedIndex();
                int index2 = list2.getSelectedIndex();
                listModel.remove(index);
                listModel2.remove(index2);
                int size = listModel.getSize();
                int size2 = listModel2.getSize();
                if (size == 0) {
                //Nobody's left, disable firing.
                    fireButton.setEnabled(false);
                } else {
                //Adjust the selection.
                    if (index == listModel.getSize())//removed item in last position
                        index--;
                    list.setSelectedIndex(index);   //otherwise select same index
                if (size2 == 0) {
                //Nobody's left, disable firing.
                    fireButton.setEnabled(false);
                } else {
                //Adjust the selection.
                    if (index2 == listModel2.getSize())//removed item in last position
                        index2--;
                    list2.setSelectedIndex(index2);   //otherwise select same index
        //This listener is shared by the text field and the hire button
        class HireListener implements ActionListener {
            public void actionPerformed(ActionEvent e) {
                //User didn't type in a name...
                if (employeeName.getText().equals("")) {
                    Toolkit.getDefaultToolkit().beep();
                    return;
                //User didn't type in a percent...
                if (percent.getText().equals("")) {
                    Toolkit.getDefaultToolkit().beep();
                    return;
                int index = list.getSelectedIndex();
                int index2 = list2.getSelectedIndex();
                int size = listModel.getSize();
                int size2 = listModel2.getSize();
                //If no selection or if item in last position is selected,
                //add the new hire to end of list, and select new hire.
                if (index == -1 || (index+1 == size)) {
                    listModel.addElement(employeeName.getText());
                    list.setSelectedIndex(size);
                //Otherwise insert the new hire after the current selection,
                //and select new hire.
                } else {
                    listModel.insertElementAt(employeeName.getText(), index+1);
                    list.setSelectedIndex(index+1);
                //If no selection or if item in last position is selected,
                //add the new hire to end of list, and select new hire.
                if (index2 == -1 || (index2+1 == size2)) {
                    listModel2.addElement(String.valueOf(per.getValue()));
                    list2.setSelectedIndex(size2);
                //Otherwise insert the new hire after the current selection,
                //and select new hire.
                } else {
                    listModel2.insertElementAt(String.valueOf(per.getValue()), index2+1);
                    list2.setSelectedIndex(index2+1);
        public void valueChanged(ListSelectionEvent e) {
            if (e.getValueIsAdjusting() == false) {
                if (list.getSelectedIndex() == -1) {
                //No selection, disable fire button.
                    fireButton.setEnabled(false);
                    employeeName.setText("");
                } else {
                //Selection, update text field.
                    fireButton.setEnabled(true);
                    String name = list.getSelectedValue().toString();
                    employeeName.setText(name);
                if (list2.getSelectedIndex() == -1) {
                //No selection, disable fire button.
                    fireButton.setEnabled(false);
    //                percent.setText("");
                } else {
                //Selection, update text field.
                    fireButton.setEnabled(true);
                    String name = list2.getSelectedValue().toString();
    //                percent.setText(name);
        public static void main(String s[]) {
            JFrame frame = new ListDemo();
            frame.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
            frame.pack();
            frame.setVisible(true);
    }

  • Short code causes a strange problem - About the list again -- please read!

    Hi again people. Maybe you remember my project - has a list, that you can search thru using a text field. During the work I got stuck on a strange problem ( Again :-( ) My app has one text field, one combo box, one list and a text field once more. The code should do the following ->
    *1. Load the list, no problem with that.*
    *2. Show the elements of the list, that match the selected group in the combo box,no problem.*
    *3. Search thru the list using the text field,no problem.*
    4. When the user selects an element from the list, it should display its info in the second text field. This also works fine, but when after looking at info of one of the elements the things on numbers 2 and 3 ( look up! ) stop working. I must say that everything works fine until user selects an element from the list. I couldnt understand this kind of behavior so I am asking you to help me please.
    The code is very simple:
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    class the_window extends JFrame implements DocumentListener, ItemListener, ListSelectionListener {
        FileReader reader;
        String data_base[][];
        String first_pass[];
        int number_of_elements;
        DefaultListModel dflm = new DefaultListModel();
        JList list;
        JTextField text_field = new JTextField();
        JTextField info_field = new JTextField();
        String groups[] = {"1. group" , "2. group"};
        JComboBox groups_cmbx = new JComboBox(groups);
        the_window(){
            super("the Window!");
            JPanel panel = new JPanel(null);
            Container c = this.getContentPane();
            c.add(panel);
            text_field.setBounds(10,10,170,25);
            text_field.getDocument().addDocumentListener(this);
            panel.add(text_field);
            groups_cmbx.setBounds(10,45,170,25);
            groups_cmbx.addItemListener(this);
            panel.add(groups_cmbx);
            list = new JList(dflm);
            list.setBounds(10,90,170,190);
            list.setFixedCellHeight(20);
            list.addListSelectionListener(this);
            panel.add(list);
            info_field.setBounds(10,280,170,25);
            panel.add(info_field);
            load_the_base();
            refresh();
            this.setSize(190,350);
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            this.setResizable(false);
            this.setVisible(true);
        public void itemStateChanged(ItemEvent e){
            refresh();
        public void valueChanged(ListSelectionEvent e){
            String str = (String) dflm.getElementAt(list.getSelectedIndex());
            int index = 0;
            for(int i = 0; i < number_of_elements; i++){
                if(str.equals(data_base[0])){
    index = i;
    break;
    info_field.setText(data_base[index][1]);
    private void load_the_base(){
    String data = "";
    try{
    reader = new FileReader("data.txt";);
    int r = 0;
    while((r = reader.read()) != -1){
    char c = (char) r;
    data += c;
    reader.close();
    }catch(IOException e){}
    first_pass = data.split(";");
    number_of_elements = first_pass.length;
    data_base = new String[number_of_elements][];
    for(int i = 0; i<number_of_elements; i++){
    data_base[i] = first_pass[i].split("#");
    private void refresh(){
    String search_str = text_field.getText();
    int selektovano = groups_cmbx.getSelectedIndex();
    dflm.clear();
    for(int i = 0; i < number_of_elements; i++){
    int grupa = Integer.parseInt(data_base[i][2]);
    if(grupa == selektovano){
    String at_the_moment = data_base[i][0]; // if you change this to String at_the_moment = data_base[i][1]; it works perfectly
    if(at_the_moment.startsWith(search_str)){
    dflm.addElement(at_the_moment);
    public void changedUpdate(DocumentEvent e){
    refresh();
    public void removeUpdate(DocumentEvent e){
    refresh();
    public void insertUpdate(DocumentEvent e){
    refresh();
    public class Main {
    public static void main(String[] args) {
    JFrame f = new the_window();
    Now, can you please tell me whats wrong with this?
    For the "data.txt" make a new text file using *notepad* and copy the following line into the document:
    _1. element#1. info#0;2. element#2. info#0;3. element#3. info#1;4. element#4. info#1;5. element#5. info#1;_                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    Darryl.Burke wrote:
    Keith, thanks for making that readable. So here's the diagnosis -
    In the refresh() method, calling defaultListModel.clear() results in a valueChanged(...) event in which this method calldefaultListModel.getElementAt(list.getSelectedIndex())results in the exception noted, as getSelectedIndex returns -1, the list being empty... you can't getElementAt(-1).
    I haven't analyzed all the code nor checked whether is now works as desired, but this small change to valueChanged counters the exception being thrown.   public void valueChanged(ListSelectionEvent e) {
    infoField.setText(""); // do this unconditionally
    if (list.getSelectedIndex() != -1) {
    String value = (String)defaultListModel.getElementAt(list.getSelectedIndex());
    for(int i = 0; i < numFields; i++){
    if(value.equals(matrix[0])){
    infoField.setText(matrix[i][1]);
    break;
    db
    Yea! You were right! I didnt think that calling *list_model.clear();* will result in calling *valueChanged()* ........
    That was some *clear()* thinking :-) Thank you!
    corlettk wrote:
    I cleaned up some variable & method names (tut tut), imports (very naighty), and some thread stuff... but it remains fundamentally the same codeIs it so important to "clean" the imports? How much does it slow down the loading time? Should I do this on all my projects, because they are all "very naighty"?
    ps. Thanks to all that gave some help to answering this strange question :-)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

Maybe you are looking for