JList Help

Can someone please help me with this...
I want to do the following things in JList, what method should i use?
1. remove a selected item
2. add new itme into the list
3. get the selected item
4. get all item
5. get the size of the list
hope someone can help me with this..
Thx

Hi,
if you are normally working with JList (it is different to java.awt.List).
The best way for this will be:
having a Vector with all you items in it. construct a JList with the constructor which has a vector as parameter.
1. remove it from the vector and set the new vector to the jlist (setListData)
2. add to vector (see above)
3. getSelectedIndex()
4.the items are in the vector
5. the size is the size of the vector
regards

Similar Messages

  • JOptionPane and JList HELP!!!

    Hi there,
    I want to be able to use a JOptionPane and add these elements to my JList component. I know how to add elements to it through the source code but am not able to get a user to inout values into this JList. 've got my JOptionPane running by using the following code:
    public void actionPerformed(ActionEvent ae) {
           if(ae.getActionCommand().equals("New Player")){
                s1 = JOptionPane.showInputDialog("Enter player: ");
                list.append(s1);
           repaint();
      }I want the values taken from this Prompt and be shown in my JList. I tried doing:
    list.addElement(s1);
    list.append(s1);
    I tried looking at the Java API website but didn't find it helpful at all of what I'm trying to do.

    I keep getting an error on the line where it says:
    list.add(s1);And even when I try:
    list.addElement(s1);Still same error. Is it a different way of doing it?
    Thanks for any response

  • JList Help - Adding Element

    Hi,
    I have a class that has the JList and its model(the DefaultListModel) . I initialize the JList with this model. I also have a second class that has a form with textarea and a button. i want to add the text from the textarea in this second class to the JList in the first class. Anytime i click the "add" button i don't see the text been added to the JList. Though I can print the elements of the list in the the second class. Meaning i can print in the second class the elements of the JList.
    I read on the net that i should call "fireContentsChanged()" on the list model after i add the text to make it visible, but there is no such method. What should i do to make the added text visible in the list or to update the list so that the newly added text is visible?
    Thanks.

    To get better help sooner, post a [_SSCCE_|http://mindprod.com/jgloss/sscce.html] that clearly demonstrates your problem.
    Use code tags to post codes -- [code]CODE[/code] will display asCODEOr click the CODE button and paste your code between the {code} tags that appear.
    db

  • JList Help please

    Hi,
    I've got a JList that uses a cellRenderer that I have defined.
    This cell renderer is like so:
    class MyCellRenderer extends JPanel implements ListCellRenderer
    The cell renderer works fine and displays all of the data that I need it to in my list.
    The only problem is that each cell is of differing size and each cell is centre aligned when added to the list.
    Call me stupid but I can't find any way to make it so that each of the cell is left aligned. Surely there must be an easy way to do this.. i've tried everything i can think of.
    Any help appriciated.
    Andy

    The alignment is probably going to depend on the layout of the panel.
    The size is probably going to depend on the minimum sizes of the components it contains, but again this is going to depend on the layout of the panel.

  • Need help in storing data from JList into a vector

    need help in doing the following.-
    alright i click a skill on industryskills Jlist and press the add button and it'll be added to the applicantskills Jlist. how do i further store this data that i added onto the applicantskills JList into a vector.
    here are the codes:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.text.*;
    import java.util.*;
    import java.util.Vector;
    import javax.swing.JScrollPane.*;
    //import javax.swing.event.ListSelectionListener;
    public class Employment extends JFrame
            //declare class variables
            private JPanel jpApplicant, jpEverything,jpWEST, jpCENTRE, jpEAST, jpAddEditDelete,
                                       jpCentreTOP, jpCentreBOT, jpEastTOP, jpEastCENTRE, jpEastBOT,
                                       jpBlank1, panel1, panel2, panel3, panel4,jpBottomArea,
                                       jpEmptyPanelForDisplayPurposes;
            private JLabel jlblApplicantForm, jlblAppList, jlblName, jlblPhone,
                                       jlblCurrentSalary, jlblPassword, jlblDesiredSalary,
                                       jlblNotes, jlblApplicantSkills, jlblIndustrySkills,
                                       jlblBlank1, jlblBlank2, ApplicantListLabel,
                                       NotesListLabel, ApplicantSkillsLabel,
                                       IndustrySkillsLabel,jlblEmptyLabelForDisplayPurposes;  
            private JButton jbtnAdd1, jbtnEdit, jbtnDelete, jbtnSave, jbtnCancel,
                                            jbtnAdd2, jbtnRemove;
            private JTextField jtfName, jtfPhone, jtfCurrentSalary, jtfPassword,
                                               jtfDesiredSalary;
              private JTabbedPane tabbedPane;
            private DefaultListModel /*listModel,*/listModel2;
              String name,password,phone,currentsalary,desiredsalary,textareastuff,NotesText;
              String selectedname;
            final JTextArea Noteslist= new JTextArea();;
            DefaultListModel listModel = new DefaultListModel();
            JList ApplicantSkillsList = new JList(listModel);
           private ListSelectionModel listSelectionModel;
            JList ApplicantList, /*ApplicantSkillsList,*/ IndustrySkillsList;
            //protected JTextArea NotesList;    
                    //Vector details = new Vector();
                  Vector<StoringData> details = new Vector<StoringData>();             
                public static void main(String []args)
                    Employment f = new Employment();
                    f.setVisible(true);
                    f.setDefaultCloseOperation(EXIT_ON_CLOSE);
                    f.setResizable(false);
                }//end of main
                    public Employment()
                            setSize(800,470);
                            setTitle("E-commerce Placement Agency");
                                  Font listfonts = new Font("TimesRoman", Font.BOLD, 12);
                            JPanel topPanel = new JPanel();
                            topPanel.setLayout( new BorderLayout() );
                            getContentPane().add( topPanel );
                            createPage1();
                            createPage2();
                            createPage3();
                            createPage4();
                            tabbedPane = new JTabbedPane();
                            tabbedPane.addTab( "Applicant", panel1 );
                            tabbedPane.addTab( "Job Order", panel2 );
                            tabbedPane.addTab( "Skill", panel3 );
                            tabbedPane.addTab( "Company", panel4 );
                            topPanel.add( tabbedPane, BorderLayout.CENTER );
            public void createPage1()//PAGE 1
                 /*******************TOP PART********************/
                            panel1 = new JPanel();
                            panel1.setLayout( new BorderLayout());
                                  jpBottomArea = new JPanel();
                                  jpBottomArea.setLayout(new BorderLayout());
                            jpApplicant= new JPanel();
                            jpApplicant.setLayout(new BorderLayout());
                            Font bigFont = new Font("TimesRoman", Font.BOLD,24);
                            jpApplicant.setBackground(Color.lightGray);
                            jlblApplicantForm = new JLabel("\t\t\t\tAPPLICANT FORM  ");
                            jlblApplicantForm.setFont(bigFont);
                            jpApplicant.add(jlblApplicantForm,BorderLayout.EAST);
                            panel1.add(jpApplicant,BorderLayout.NORTH);
                            panel1.add(jpBottomArea,BorderLayout.CENTER);
           /********************************EMPTY PANEL FOR DISPLAY PURPOSES*************************/
                               jpEmptyPanelForDisplayPurposes = new JPanel();
                               jlblEmptyLabelForDisplayPurposes = new JLabel(" ");
                               jpEmptyPanelForDisplayPurposes.add(jlblEmptyLabelForDisplayPurposes);
                               jpBottomArea.add(jpEmptyPanelForDisplayPurposes,BorderLayout.NORTH);
           /*****************************************WEST*********************************/             
                            jpWEST = new JPanel();                 
                            jpWEST.setLayout( new BorderLayout());
                            //Applicant List
                                  listModel2=new DefaultListModel();
                                  ApplicantList = new JList(listModel2);
                                listSelectionModel = ApplicantList.getSelectionModel();
                                listSelectionModel.addListSelectionListener(new SharedListSelectionHandler());
                                JScrollPane scrollPane3 = new JScrollPane(ApplicantList);
                                  ApplicantList.setPreferredSize(new Dimension(20,40));
                                 scrollPane3.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);                                             
                                scrollPane3.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
                            ApplicantListLabel = new JLabel( "Applicant List:");
                            jpWEST.add(ApplicantListLabel,"North"); 
                            jpWEST.add(scrollPane3,"Center");
                            jpBottomArea.add(jpWEST,BorderLayout.WEST);
                            /*********CENTRE*********/
                            jpCENTRE = new JPanel();
                            jpCENTRE.setLayout(new GridLayout(2,1));
                            jpCentreTOP = new JPanel();
                            jpBottomArea.add(jpCENTRE,BorderLayout.CENTER);
                            jpCENTRE.add(jpCentreTOP);
                            jpCentreTOP.setLayout(new GridLayout(6,2));
                              //Creating labels and textfields
                            jlblName = new JLabel( "Name:");
                            jlblBlank1 = new JLabel ("");
                            jtfName = new JTextField(18);
                            jlblBlank2 = new JLabel("");
                            jlblPhone = new JLabel("Phone:");
                            jlblCurrentSalary = new JLabel("Current Salary:");
                            jtfPhone = new JTextField(13);
                            jtfCurrentSalary = new JTextField(7);
                            jlblPassword = new JLabel("Password:");
                            jlblDesiredSalary = new JLabel("Desired Salary:");
                            jtfPassword = new JTextField(13);
                            jtfDesiredSalary = new JTextField(6);
                              //Add labels and textfields to panel
                            jpCentreTOP.add(jlblName);
                            jpCentreTOP.add(jlblBlank1);
                            jpCentreTOP.add(jtfName);
                            jpCentreTOP.add(jlblBlank2);
                            jpCentreTOP.add(jlblPhone);
                            jpCentreTOP.add(jlblCurrentSalary);
                            jpCentreTOP.add(jtfPhone);
                            jpCentreTOP.add(jtfCurrentSalary);
                            jpCentreTOP.add(jlblPassword);
                            jpCentreTOP.add(jlblDesiredSalary);
                            jpCentreTOP.add(jtfPassword);
                            jpCentreTOP.add(jtfDesiredSalary);
                            //Noteslist
                            jpCentreBOT = new JPanel();
                            jpCentreBOT.setLayout( new BorderLayout());
                            jpCENTRE.add(jpCentreBOT);
                            jpBlank1 = new JPanel();
                             //     Noteslist = new JTextArea(/*Document doc*/);
                            JScrollPane scroll3=new JScrollPane(Noteslist);
                                scroll3.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);                                             
                                scroll3.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
                            NotesListLabel = new JLabel( "Notes:");
                            jpCentreBOT.add(NotesListLabel,"North"); 
                            jpCentreBOT.add(scroll3,"Center");
                            jpCentreBOT.add(jpBlank1,"South");
                            jpBottomArea.add(jpCENTRE,BorderLayout.CENTER);
                            /**********EAST**********/
                            //Applicant Skills Panel
                            //EAST ==> TOP
                            jpEAST = new JPanel();
                            jpEAST.setLayout( new BorderLayout());
                            jpEastTOP = new JPanel();
                            jpEastTOP.setLayout( new BorderLayout());
                            ApplicantSkillsLabel = new JLabel( "Applicant Skills");
                            JScrollPane scrollPane1 = new JScrollPane(ApplicantSkillsList);
                               scrollPane1.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);                                             
                              scrollPane1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);                                             
                            ApplicantSkillsList.setVisibleRowCount(6);
                            jpEastTOP.add(ApplicantSkillsLabel,"North"); 
                            jpEastTOP.add(scrollPane1,"Center");
                            jpEAST.add(jpEastTOP,BorderLayout.NORTH);
                            jpBottomArea.add(jpEAST,BorderLayout.EAST);
                            //Add & Remove Buttons
                            //EAST ==> CENTRE
                            jpEastCENTRE = new JPanel();
                            jpEAST.add(jpEastCENTRE,BorderLayout.CENTER);
                            jbtnAdd2 = new JButton("Add");
                            jbtnRemove = new JButton("Remove");
                            //add buttons to panel
                            jpEastCENTRE.add(jbtnAdd2);
                            jpEastCENTRE.add(jbtnRemove);
                            //add listener to button
                           jbtnAdd2.addActionListener(new Add2Listener());
                           jbtnRemove.addActionListener(new RemoveListener());
                            //Industry Skills Panel
                            //EAST ==> BOTTOM
                            jpEastBOT = new JPanel();
                            jpEastBOT.setLayout( new BorderLayout());
                           String[] data = {"Access97", "Basic Programming",
                           "C++ Programming", "COBOL Programming",
                           "DB Design", "Fortran programming"};
                           IndustrySkillsList = new JList(data);
                           JScrollPane scrollPane = new JScrollPane(IndustrySkillsList);
                           scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);                                             
                           scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
                           IndustrySkillsLabel = new JLabel( "Industry Skills:");
                           jpEastBOT.add(IndustrySkillsLabel,"North"); 
                           jpEastBOT.add(scrollPane,"Center");
                           jpEAST.add(jpEastBOT,BorderLayout.SOUTH);
                            //BOTTOM
                            jpAddEditDelete= new JPanel();
                            jbtnAdd1=       new JButton("Add");
                            jbtnEdit=       new JButton("Edit");
                            jbtnDelete=     new JButton("Delete");
                            jbtnSave=       new JButton("Save");
                            jbtnCancel=     new JButton("Cancel");
                            jpAddEditDelete.add(jbtnAdd1);
                            jpAddEditDelete.add(jbtnEdit);
                            jpAddEditDelete.add(jbtnDelete);
                            jpAddEditDelete.add(jbtnSave);
                            jpAddEditDelete.add(jbtnCancel);
                               jbtnEdit.addActionListener(new EditListener());
                               jbtnDelete.addActionListener(new DeleteListener());
                                jbtnEdit.addActionListener(new EditListener());
                            jbtnAdd1.addActionListener(new Add1Listener());
                            jbtnCancel.addActionListener(new CancelListener());
                            jpBottomArea.add(jpAddEditDelete,BorderLayout.SOUTH);
            public void createPage2()//PAGE 2
                    panel2 = new JPanel();
                    panel2.setLayout( new GridLayout(1,1) );
                    panel2.add( new JLabel( "Sorry,under construction" ) );
            public void createPage3()//PAGE 3
                    panel3 = new JPanel();
                    panel3.setLayout( new GridLayout( 1, 1 ) );
                    panel3.add( new JLabel( "Sorry,under construction" ) );
            public void createPage4()//PAGE 4
                    panel4 = new JPanel();
                    panel4.setLayout( new GridLayout( 1, 1 ) );
                    panel4.add( new JLabel( "Sorry,under construction" ) );
            public class Add1Listener implements ActionListener
            public void actionPerformed(ActionEvent e)
                    name = jtfName.getText();
                    password = jtfPassword.getText();
                    phone = jtfPhone.getText();
                    currentsalary = jtfCurrentSalary.getText();
                    int i= Integer.parseInt(currentsalary);
                    desiredsalary = jtfDesiredSalary.getText();
                    int j= Integer.parseInt(desiredsalary);
                       StoringData person = new StoringData(name,password,phone,i,j);
                   //     StoringData AppSkillsList = new StoringData(listModel);
                    details.add(person);
                 //     details.add(AppSkillsList);
                  listModel2.addElement(name);
                    jtfName.setText("");
                    jtfPassword.setText("");
                    jtfPhone.setText("");
                    jtfCurrentSalary.setText("");
                    jtfDesiredSalary.setText("");
    //                NotesList.setText("");
            public class Add2Listener implements ActionListener
                    public void actionPerformed(ActionEvent e)
                           String temp1;
                           temp1 = (String)IndustrySkillsList.getSelectedValue();
                           listModel.addElement(temp1);
            public class RemoveListener implements ActionListener
                    public void actionPerformed(ActionEvent e)
                            int index = ApplicantSkillsList.getSelectedIndex();
                                listModel.remove(index);
            public class EditListener implements ActionListener
                    public void actionPerformed(ActionEvent e)
                            jtfName.setEditable(true);
                            jtfPassword.setEditable(true);
                            jtfPhone.setEditable(true);
                            jtfCurrentSalary.setEditable(true);
                            jtfDesiredSalary.setEditable(true);
                            Noteslist.setEditable(true);
                            jbtnAdd2.setEnabled(true);               
                            jbtnRemove.setEnabled(true);
                            jbtnSave.setEnabled(true);
                            jbtnCancel.setEnabled(true);                     
            public class DeleteListener implements ActionListener
                    public void actionPerformed(ActionEvent e)
                        int index1 = ApplicantList.getSelectedIndex();
                            listModel2.remove(index1);
            public class SaveListener implements ActionListener
                    public void actionPerformed(ActionEvent e)
            public class CancelListener implements ActionListener
                    public void actionPerformed(ActionEvent e)
                    jtfName.setText("");
                    jtfPassword.setText("");
                    jtfPhone.setText("");
                    jtfCurrentSalary.setText("");
                    jtfDesiredSalary.setText("");                         
            public class SharedListSelectionHandler implements ListSelectionListener
            public void valueChanged(ListSelectionEvent e)
             selectedname =ApplicantList.getSelectedValue().toString();
             StoringData selectedPerson = null;
             jtfName.setEditable(false);
             jtfPassword.setEditable(false);
             jtfPhone.setEditable(false);
             jtfCurrentSalary.setEditable(false);
             jtfDesiredSalary.setEditable(false);                                 
             Noteslist.setEditable(false);
             jbtnAdd2.setEnabled(false);               
             jbtnRemove.setEnabled(false);
             jbtnSave.setEnabled(false);
             jbtnCancel.setEnabled(false);
                   for (StoringData person : details)
                          if (person.getName1().equals(selectedname))
                                 selectedPerson = person;
                                 jtfName.setText(person.getName1());
                                 jtfPassword.setText(person.getPassword1());
                              jtfPhone.setText(person.getPhone1());
                              //String sal1 = Integer.parseString(currentsalary);
                             // String sal2 = Integer.parseString(desiredsalary);
                             // jtfCurrentSalary.setText(sal1);
                             // jtfDesiredSalary.setText(sal2);
                                 break;
                   //     if (selectedPerson != null)
    }

    Quit posting 300 line programs to ask a question. We don't care about your entire application. We only care about code that demonstrates your current problem. We don't want to read through 300 lines to try and find the line of code that is causing the problem.
    If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program (SSCCE) that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    And don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the code retains its original formatting.
    Here is a simple SSCCE. Now make your changes and if you still have problems you have something simple to post. If it works then you add it to your real application.
    Learn to simplify your problem by simplifying the code.
    import java.awt.*;
    import javax.swing.*;
    public class ListTest2 extends JFrame
         JList list;
         public ListTest2()
              String[] numbers = { "one", "two", "three", "four", "five", "six", "seven" };
              list = new JList( numbers );
              JScrollPane scrollPane = new JScrollPane( list );
              getContentPane().add( scrollPane );
         public static void main(String[] args)
              ListTest2 frame = new ListTest2();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.setSize(200, 200);
              frame.setLocationRelativeTo( null );
              frame.setVisible( true );
    }

  • How to do the multiple-line String at JList? help!

    i need some code to multiple-line String at JList.
    i know that it is can be done by html code.
    example:
    <p>line1</p><p>line2</p>
    but if i use that html code...
    i face another problem to my JList..
    it cannot set the font use the ListCellRenderer..
    like:
    public Component getListCellRendererComponent(
    JList list,
    Object value,
    int index,
    boolean isSelected,
    boolean cellHasFocus)
    Color newColor = new Color(230, 230, 230);
    setIcon(((DisplayItem)value).getIcon());
    setText(((DisplayItem)value).getChat());
    setFont(((DisplayItem)value).getFont());
    setBackground(isSelected ? newColor : Color.white);
    setForeground(isSelected ? Color.black : Color.black);
    if (isSelected) {
    setBorder(
    BorderFactory.createLineBorder(
    Color.red, 2));
    } else {
    setBorder(
    BorderFactory.createLineBorder(
    list.getBackground(), 2));
    return this;
    all my JList will be html type...
    i don't want that happen..can be another method to do that multiple-line String in JList??
    i also need to set a icon image between string in the JList. anyone get idea??
    i need ur help!
    thank you.

    I think you should create/override several methods like setText(String), setIcons(Icon[]), paintComponent(Graphics), getMinimumSize(), getPreferredSize(), etc.
    I would like to code like below...:class MultilineLabel extends JLabel {
        private String[] text = null;
        private ImageIcon[] icons = null;
        public void setText( String newText ) {
            // It overrides JLabel.setText( String )
            // Tokenize newText with line-separator
            // and put each text into the 'text' array.
        public void setIcons( Icon[] newIcon ) {
            // It is similar to JLabel.setIcon( Icon ) method,
            // but it receives an array of Icon-s. Set these icons to 'icons' variable.
        public void paintComponent( Graphics g ) {
            // It overrides JComponent.paintComponent( Graphics ) method.
            super.paintComponent( g );
            if ( text != null && icons != null ) {
                int icon_x = 0;
                int text_x = 0;
                int y = 0;
                // draw customized content..
                for ( int i=0; i<text.length; i++ ) {
                    // compute x and y locations
                    // icon_x = ...
                    // text_x = ...
                    // y = ...
                    // and draw it!
                    g.drawString( text[ i ], text_x, y );
                    icon[ i ].paintIcon( this, g, icon_x, y );
        public Dimension getMinimumSize() {
            int width = super.getMinimumSize().width;
            int height = ... // I think you must compute it with 'text' and 'icons'' arrays.
            return new Dimension( width, height );
        public Dimension getPreferredSize() {
            int width = super.getPreferredSize().width;
            int height = ...
            return new Dimension( width, height );
    }I think that code-structure above is the minimum to implement your requirements. (Of course if you want to implement it :)
    Good luck and let me know it works or not. :)

  • Button Event Handler in a JList, Please help.

    Hi everyone,
    I have created a small Java application which has a JList. The JList uses a custom cell renderer I named SmartCellRenderer. The SmartCellRenderer extends JPanel and implements the ListCellRenderer. I have added two buttons on the right side inside the JPanel of the SmartCellRenderer, since I want to buttons for each list item, and I have added mouse/action listeners for both buttons. However, they don't respond. It seems that the JList property overcomes the buttons underneath it. So the buttons never really get clicked because before that happens the JList item is being selected beforehand. I've tried everything. I've put listeners in the Main class, called Editor, which has the JList and also have listeners in the SmartCellRenderer itself and none of them get invoked.
    I also tried a manual solution. Every time the event handler for the JList was invoked (this is the handler for the JList itself and not the buttons), I sent the mouse event object to the SmartCellRenderer to manually check if the point the click happened was on one of the buttons in order to handle it.
    I used:
    // Inside SmartCellRenderer.java
    // e is the mouse event object being passed from the Editor whenever
    // a JList item is selected or clicked on
    Component comp = this.getComponent (e.getX(), e.getY())
    if(!(comp instanceof JButton)) {
              System.out.println("Recoqnized Event, but not a button click...");
              //return;
    } else {
              System.out.println("Recognized Event, IT IS A MOUSE CLICK, PROCESSING...");
              System.out.println("VALUE: "+comp.toString());
    What I realized is that not only this still doesn't work (it never realizes the component as a JButton) it also throws an exception for the last line saying comp is null. Meaning with the passed x,y position the getComponent() returns a null which happens when the coordinates passed to it are outside the range of the Panel. Which is a whole other problem?
    I have yet to find an example on the web, using Google, that demonstrated using buttons inside a JList.
    Can anyone help me with this. Thanks.

    A renderer is not a component, so you can't click on it. A renderer is just used to paint a representation of a component at a certain position in your JList.
    I have yet to find an example on the web, using Google, that demonstrated using buttons inside a JList.Thats probably because this is not a common design. The following two designs are more common:
    a) Create a separate panel for your JButtons. Then when you click on the button it would act on each selected row in the JList
    b) Or maybe like windows explorer. Select the items in the list and then use a JPopupMenu to perform the desired functionality.
    I've never tried to add a clickable button to a panel, but this [url http://forum.java.sun.com/thread.jspa?threadID=573721]posting shows one way to add a clickable JButton as a column in a JTable. You might be able to use some of the concepts to add 2 button to the JPanel or maybe you could use a JTable with 3 columns, one for your data and the last two for your buttons.

  • JList bug help

    there's a bug in JAVA about JList that when you select an item the selectvalue sends it twice
    i got an answer but it doesn't work
    i build a Jlist from a list of items in a DB, first there put in an string[] then in a vector & then in the JList
    can anyone please help me

    Swing related questions should be posted in the Swing forum.
    there's a bug in JAVA about JList that when you select an item the selectvalue sends it twiceThis is not a bug.
    i got an answer but it doesn't workIts nice of you to share this answer. Are we supposed to quess what you have attempted to do.
    can anyone please help me Read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/list.html]How to Use Lists for a working example on how to write your ListSelectionListener.

  • Help needed, stuck in a DnD JList problem

    Hi guys
    I got this code from internet and I was really expecting it would work, but it is not really transferring my Object to the other JList.
    I someone can help me I would appreciate that very much, below is the code, to the Model and to the Transfer.
    Model
    public class TabVernizListModel extends AbstractListModel {
        ArrayList<TabelaVerniz> lista;
        public TabVernizListModel(ArrayList<TabelaVerniz> lista) {
            this.lista = lista;
        public TabVernizListModel() {
            lista = new ArrayList<TabelaVerniz>();
        public Object getElementAt(int index) {
            Object item = null;
            if (lista != null) {
                item = lista.get(index);
            return item;
        public Integer getSelectedIndex(TabelaVerniz item) {
            int index = lista.indexOf(item);
            return index;
        public int getSize() {
            int size = 0;
            if (lista != null) {
                size = lista.size();
            return size;
        public void remove(int index) {
            fireIntervalRemoved(this, index, index);
            lista.remove(index);
        // This is not really working, does not update the 2nd List
        public void add(TabelaVerniz tabela) {
            if (lista == null) {
                lista = new ArrayList<TabelaVerniz>();
            lista.add(tabela);
            int index = this.getSelectedIndex(tabela);
            super.fireIntervalAdded(this, lista.size() - 1, lista.size() - 1);
    The Transfer:
    public class TabVernizTransferHandler extends TransferHandler {
        JList listaEsquerda;
        JList listaDireita;
        // This transfer handler needs to know about the two JLists !
        public TabVernizTransferHandler(JList leftList, JList rightList) {
            super();
            listaEsquerda = leftList;
            listaDireita = rightList;
        @Override
        public boolean importData(JComponent component, Transferable trasferedObject) {
            JList lista = (JList) component;
            try {
                int sourceIndex = Integer.parseInt((String) trasferedObject.getTransferData(DataFlavor.stringFlavor));
                // figure out which is the source and which is the dest.
                TabVernizListModel source;
                TabVernizListModel dest;
                if (lista == listaEsquerda) {
                    source = (TabVernizListModel) listaDireita.getModel();
                    dest = (TabVernizListModel) listaEsquerda.getModel();
                } else {
                    source = (TabVernizListModel) listaEsquerda.getModel();
                    dest = (TabVernizListModel) listaDireita.getModel();
                // get the source object
                TabelaVerniz tabela = (TabelaVerniz) source.getElementAt(sourceIndex);
                // add it to the other model.
                dest.add(tabela);
                // and remove from the source
                source.remove(sourceIndex);
            } catch (Exception ex) {
                ex.printStackTrace();
                System.out.println("Import failed!");
                return (false);
            return (true);
        @Override
        protected Transferable createTransferable(JComponent c) {
            JList jl = (JList) c;
            // we want the currently selected index
            Integer index = new Integer(jl.getSelectedIndex());
            // and we transfer it as a string
            Transferable t = new StringSelection(index.toString());
            return t;
        @Override
        public int getSourceActions(JComponent c) {
            return MOVE;
        @Override
        public boolean canImport(JComponent c, DataFlavor[] flavors) {
            for (int i = 0; i < flavors.length; i++) {
                if (flavors.getHumanPresentableName().equals("Unicode String")) {
    return (true);
    return (false);
    }Can anyone point what is wrong here?
    When I drag from the left list to the right list it just don't drop.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    The Swing tutorial on Drag and Drop has a working example with a JList.

  • Need help c JList & File opening

    I have several a JLists from which I've listed files on my drive. I wish to be able to open/run the files(eg word documents/excel/pdf) when the file of choice is double clicked. I want the file to be opened to be based on the JList choice. Please help!

    It is bad style and against the etiquette in here to post the same question more than once. For Dos and Don'ts read this:
    http://www.mektrix.2ya.com/answers.html

  • JList ListCellRenderer Help

    Hello All,
    I have a small query in regards to a ListCellRenderer implementation.
    I have my own ListCellRenderer implementation, and it is working fine in regards to bolding text, colors and so on. But I was wondering about how I would go making a nice "glowing" effect on the mouseover event of the List item.
    I have been a web programmer for a while, and have had many nice experiences with JavaScript and using timing events, to slowly change the color of an HTML element, to give it that glowing effect.
    I was kind of hoping to do the same for a JList, is there anyone out there that has had experiences with this kind of thing?
    Any help is appreciated, I will also post if I find anything on my own.
    Cheers,
    Mark

    I've no idea of what glowing effect you are after, but I was bored and have been playing with timers and colors and came up with this effect. If you develop your glow effect, please post your code so we can play with it.
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.BorderFactory;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
    import javax.swing.Timer;
    class GlowSwing2 extends JPanel
        private static final int TIMER_PERIOD = 60;
        private static final int DIMEN = 400;
        private static final int GRID_SIZE = 5;
        private static final int COLOR_STEPS = 16;
        private Color currentColor = Color.black;
        private Color originalColor = Color.black;
        private int colorIndex = 0;
        private JLabel[][] labels = new JLabel[GRID_SIZE][GRID_SIZE];
        private JLabel currentLabel = null;
        private Timer timer = new Timer(TIMER_PERIOD, new MyTimerAction());
        private Color[] colors;
        GlowSwing2()
            setPreferredSize(new Dimension(DIMEN, DIMEN));
            int ebGap = 10;
            setBorder(BorderFactory.createEmptyBorder(ebGap, ebGap, ebGap, ebGap));
            setLayout(new GridLayout(GRID_SIZE, GRID_SIZE));
            for (int i = 0; i < GRID_SIZE; i++)
                for (int j = 0; j < GRID_SIZE; j++)
                    JLabel jl = new JLabel("Hello");
                    jl.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 24));
                    jl.addMouseListener(new LabelMouseListener());
                    add(jl);
                    labels[i][j] = jl;
            initColors();
            timer.start();
         * creates a nice sin wave of blue color
        private void initColors()
            colors = new Color[COLOR_STEPS];
            double periodStep = 2 * Math.PI / COLOR_STEPS;
            for (int i = 0; i < colors.length; i++)
                int c = (int)(256 * (Math.sin(i * periodStep) + 1)/2);
                if (c == 256)
                    c = 255;
                colors[i] = new Color(c, c, 255);
        private class LabelMouseListener extends MouseAdapter
            @Override
            public void mouseEntered(MouseEvent mEvent)
                JLabel source = (JLabel)mEvent.getSource();
                originalColor = source.getForeground();
                currentLabel = source;
                super.mouseEntered(mEvent);
            @Override
            public void mouseExited(MouseEvent mEvent)
                currentLabel = null;
                ((JLabel)mEvent.getSource()).setForeground(originalColor);
                super.mouseExited(mEvent);
        private class MyTimerAction implements ActionListener
            public void actionPerformed(ActionEvent arg0)
                myTimerAction(arg0);
         * changes the colors of the labels
         * @param arg0
        private void myTimerAction(ActionEvent arg0)
            if (currentLabel != null)
                colorIndex++;
                colorIndex %= colors.length;
                currentColor = colors[colorIndex];
                currentLabel.setForeground(currentColor);
                currentLabel.repaint();
        private static void createAndShowGUI()
            JFrame frame = new JFrame("GlowSwing Application");
            frame.getContentPane().add(new GlowSwing2());
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        public static void main(String[] args)
            SwingUtilities.invokeLater(new Runnable()
                public void run()
                    createAndShowGUI();
    }

  • Help! Need to override Page Down/Page Up in JList

    Help! Need to override Page Down/Page Up in JList...
    PgUp PgDn selects the top or bottom item in a Jlist when JList is in focus. I want PgUp and PgDn to do something different (which it does), but it still selects top or bottom items. How do I COMPLETELY remove all key listeners in the JList?
    Oliver

    Sounds like you are just adding a key listener to the list and just
    listening for PAGE_UP/PAGE_DOWN. Which is why the original behavior is
    still there: both your listener and the list's own handler are being
    invoked.
    What you might want to do instead is to either set your own action
    for PAGE_UP/PAGE_DOWN in the list's input map, and then set that action
    to your own in the list's action map, or try setting the scrollUp and
    scrollDown actions to your own action in the list's action map. Note
    that shift PAGE_UP/PAGE_DOWN are also bound, by the way.
    : jay

  • Need to add JList to a Panel Please do help me out!!!

    hi every body I need to add JList to Panel in a JTabbedPaneand having three columns by gridlayout,I have to add Jlist elements in one column and in the second one get elements from the database and place them in this column with a check and in third column i have some buttons
    in the first column add Jlist elements around 10 elements
    in the second column can we use check(true/false) for the data which we got from the database,when we uncheck here the list corresponding in the first should be disabled.
    I am using swings please give me ur ideas can this be made in different ways how can this work
    i am trying this since yesterday but could't get the correct way
    do help me out
    thanking you
    with regards

    Just when you change status of radiobutton or checkbox in its changeListener event call
    setEnabled( false );
    for the appropriate JList
    I hope that you didnt wanted me explain you entire possible code and blah blah

  • Circular  JList . Help required please

    Folks,
    I need a bit of help please.
    I have created a JList,but I want this to be circular.
    Im my JList example,I display 11 numbers,the first 5 are displayed
    when the application starts up,the user should be able to
    press the 'Down Button'and the focus shud then go to 2.
    Once the focus reaches 5,and the user presses the Down Button,
    number 1 should scroll up and the screen shud display numbers
    2 to 6.
    The user presses the Down Button again,and the screen shud display
    3 to 7.
    This way till number 11 is reached,and when the user presses
    the 'Down' button,number 1 will be displayed.
    All shud be circular.
    Attached is my code.
    Can some please suggest what needs to be coded in the
    Down Button action performed inner class??
    Or Am I overlooking something?
    public class MyCircularList extends JPanel{
        private JList list;
        private DefaultListModel listModel;
        private JButton DownButton;
        private static final String DownString = "Down";
         public MyCircularList() {
              super(new BorderLayout());
              listModel = new DefaultListModel();
              listModel.addElement("1");
              listModel.addElement("2");
              listModel.addElement("3");
              listModel.addElement("4");
              listModel.addElement("5");
              listModel.addElement("6");
              listModel.addElement("7");
              listModel.addElement("8");
              listModel.addElement("9");
              listModel.addElement("10");
              listModel.addElement("11");
              //Create the list and put it in a scroll pane.
              list = new JList(listModel);
              list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
              list.setSelectedIndex(0);
              list.setVisibleRowCount(5);
              JScrollPane listScrollPane = new JScrollPane(list);
              DownButton = new JButton(DownString);
              DownButton.setActionCommand(DownString);
               DownButton.addActionListener(new DownListener());
               JPanel buttonPane = new JPanel();
               buttonPane.setLayout(new BoxLayout(buttonPane,                                                                                           BoxLayout.LINE_AXIS));
               buttonPane.add(DownButton);
               buttonPane.add(Box.createHorizontalStrut(5));
               buttonPane.add(new JSeparator(SwingConstants.VERTICAL));
               buttonPane.add(Box.createHorizontalStrut(5));
               buttonPane.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
               add(listScrollPane, BorderLayout.CENTER);
               add(buttonPane, BorderLayout.PAGE_END);
            // Inner class to handle Button Listener.
         class DownListener implements ActionListener {
         public void actionPerformed(ActionEvent e) {
            // How to handle the circluar motion of the list???
         }  // End of actionPerformed.
         }  // End of Inner class.
         public static void main(String[] args) {
            JFrame.setDefaultLookAndFeelDecorated(true);
         JFrame frame = new JFrame("Circular List Demo");
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         JComponent newContentPane = new MyCircularList();
         newContentPane.setOpaque(true);
         frame.setContentPane(newContentPane);
         frame.pack();
         frame.setVisible(true);          

    Since you didn't include any code in your listener, I'm not sure what you want. Perhaps:
    int n=(list.getSelectedIndex()+1)%list.size();
    list.setSelectedIndex(n);
    list.ensureIndexIsVisible(n);
    But the JList keyboard support does all this automatically?

  • Help! Add Result into JTree or JList.

    Hi,
    I retrived some values from one of the table from database using ResultSet. And I want to add
    the result into the JList or JTree. Any help will be greatly appreciated.
    Thanks in advance
    Sam.
    Here is the code.
    void searchButton_actionPerformed(ActionEvent e) {
    try{
    String query = "SELECT * FROM PINFO WHERE POLICYNUMBER = '" +
    searchTextfield.getText().toUpperCase() + "'";
    ResultSet rs = Application1.stmt.executeQuery(query);
    while(rs.next()){
    pid = (rs.getInt("PID"));
    System.out.println(pid);
    catch(SQLException ex){
    System.err.println("SQLException: " + ex.getMessage());
    try{
    String query = "SELECT * FROM (UNMATCH U LEFT JOIN DOCUMENTTYPE D ON U.DOCUMENTTYPE=D.DOCNUMBER) WHERE PID = '" + pid + "'";
    ResultSet rs1 = Application1.stmt.executeQuery(query);
    while (rs1.next()){
    String documentcode = (rs1.getString("DOCUMENTCODE"));
    //************** I want to add these documentcode into the Jlist or jTree.
    System.out.println(documentcode);
    catch(SQLException s){
    System.err.println("SQLException: " + s.getMessage());
    }

    public class blah
    Vector v;
    JList j;
    public blah()
    v = new Vector();
    j = new JList(v);
    JPanel jP = new JPanel();
    jP.add(j);
    public getResults()
    v.removeAllElements();
    j.setListData(v);
    String query......
    Resultset rs = .....
    while(rs.next())
    String s = rs.getString("");
    v.add(s);
    j.setListData(v);

Maybe you are looking for

  • Null Pointer exception while invoking BPEL process

    Hi all, I am getting following exception when I am invoking a BPEL process1 (deployed in 10.1.3.1) from another BPEL Process 2 (deployed in 10.1.3.3) <env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/"> <env:Header/> <env:Body> <env:F

  • Is it possible to backup between 2 external drives?

    I've searched answers in the community and can't find one that specifcally addresses my needs. Let me first provide some context for my question. I am a writer and author, and plan to move from an early 2009 iMac to a MacBook Pro Retina. I plan to us

  • Message-Mapping transformation Error(Soap - XI - SAP)

    Hi We have a sceanio Soap <-> XI <-> SAP We could see the RFC return message from SAP but while trasforming that message to SOAP response ,we are getting the following error. We have manually run the response mapping program, it is executing fine. <S

  • ActiveSync with F5 doesn't work!

    Hello All! I'm configuring nowadays ActiveSync for mobile devices that will connect from Internet. I have URL for ActiveSync that points to External IP of our F5, let's say: https://activesync.com  After F5 gets request from Mobile Device it's being

  • 9iDS - FIND_REPORT_OBJECT doesn't find report

    What do I need to do to have FIND_REPORT_OBJECT be able to find a report? Can I specify a full path or do I need to set some configuration file to point to where it is? Here's the code I'm using to run a report from a form. PROCEDURE do_print2 IS rep