JList(remove)

Hi,
I want add an remove strings from JList on run time. I have an array assigned to JList
fileList.setListData(fileNames);
Then I am getting the name of a node form tree
Then compare it try to remove it. Seems like nothing happening
TreePath currentSelection = tree.getSelectionPath();
String tmp=currentSelection.toString();
for(int i=0; i<=fileCount; i++)
if(tmp==fileNames){
fileNames[i]=null;
while(i<fileCount){
fileNames[i]=fileNames[i+1];
i++;
fileNames[fileCount]=null;
fileCount--;
Cold you tell me how can I correct this?

Your code (plus my comments):
TreePath currentSelection = tree.getSelectionPath();
String tmp=currentSelection.toString();
for(int i=0; i<=fileCount; i++)
    if(tmp==fileNames){
fileNames[i]=null; //not needed, will be overwritten anyway
while(i<fileCount){
fileNames[i]=fileNames[i+1];
i++;
fileNames[fileCount]=null;
fileCount--;
OK, it makes a little more sense now.
try doing jList.setListData(fileNames);

Similar Messages

  • JList - Removing elements

    Is there any way you can remove all the contents of a Jlist in the one command or how would you do it.

    An alternative to Michael's suggestion would be to just create a new model:
    list.setModel(new DefaultListModel());

  • JList run time errors when removing items from list

    Hi there
    I am having trouble removing items from a JList. For a While it was working fine and now it outputs runtime errors everytime samething gets removed from the lsit
    Here is the code
    //declare
    public class Consumertab1gui extends JPanel implements ActionListener
         public static JList conList = null;
         private static DefaultListModel model = null;
    // Create a list with some items
    model = new DefaultListModel();
    conList = new JList(model);
    //set the size of cells in the list with the length of the string
    conList.setPrototypeCellValue("Lenght 1234567890");
    conList.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
    conList.addListSelectionListener(new ValueReporter());
    //set a scroll onto the list
    JScrollPane conScroll = new JScrollPane(conList);
    add(conScroll,c);
    //when the button gets pressed to drop the selected item the following code is called
    private void dropConsumer()
    int selItem=0;
    componentsV.comVRemove(conList.getSelectedValue().toString());
    selItem=conList.getSelectedIndex();
    System.out.println("No:"+(model.getSize()-1));
    System.out.println("S:"+selItem);
    remConList(selItem);
    dropCon.setEnabled(false);
    //which in turns calls this
    public void remConList(int pos)
         model.remove(pos);
    when the model.remove(pos) code is executed the following runtime errors are given:
    java.lang.NullPointerException
    at Consumertab1gui$ValueReporter.valueChanged(Consumertab1gui.java:197)
    at javax.swing.JList.fireSelectionValueChanged(JList.java:1321)
    at javax.swing.JList$ListSelectionHandler.valueChanged(JList.java:1335)
    at javax.swing.DefaultListSelectionModel.fireValueChanged(DefaultListSelectionModel.java:187)
    at javax.swing.DefaultListSelectionModel.fireValueChanged(DefaultListSelectionModel.java:167)
    at javax.swing.DefaultListSelectionModel.fireValueChanged(DefaultListSelectionModel.java:214)
    at javax.swing.DefaultListSelectionModel.removeIndexInterval(DefaultListSelectionModel.java:546)
    at javax.swing.plaf.basic.BasicListUI$ListDataHandler.intervalRemoved(BasicListUI.java:1561)
    at javax.swing.AbstractListModel.fireIntervalRemoved(AbstractListModel.java:160)
    at javax.swing.DefaultListModel.remove(DefaultListModel.java:478)
    at Consumertab1gui.remConList(Consumertab1gui.java:38)
    at Consumertab1gui.dropConsumer(Consumertab1gui.java:58)
    at Consumertab1gui.actionPerformed(Consumertab1gui.java:46)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1786)
    at javax.swing.AbstractButton$ForwardActionEvents.actionPerformed(AbstractButton.java:1839)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:420)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:258)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:245)
    at java.awt.Component.processMouseEvent(Component.java:5100)
    at java.awt.Component.processEvent(Component.java:4897)
    at java.awt.Container.processEvent(Container.java:1569)
    at java.awt.Component.dispatchEventImpl(Component.java:3615)
    at java.awt.Container.dispatchEventImpl(Container.java:1627)
    at java.awt.Component.dispatchEvent(Component.java:3477)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3483)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3198)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3128)
    at java.awt.Container.dispatchEventImpl(Container.java:1613)
    at java.awt.Window.dispatchEventImpl(Window.java:1606)
    at java.awt.Component.dispatchEvent(Component.java:3477)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:456)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:145)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:137)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:100)
    can anyone spot any mistakes in the code or suggest possible resons as to why these run time errors occur?
    Thanks
    alexis

    java.lang.NullPointerException
    at Consumertab1gui$ValueReporter.valueChanged(Consumertab1gui.java:197)The NullPointerException occurs at line 197, in the valueChanged method of your ValueReporter inner class. I have looked through your post several times but I don't see where you posted that method. Anyway, that is where you should look.
    PC&#178;

  • JPanel, jScrollPane, jLists and removing components

    I have a method that when a textfield gets the focus, I want my jScrollPane to clear out. I don't want to removeAll, but I only want to remove the 2 jLists: listCheckBox and listDescription.
    What I have below doesn't visually remove my jLists.
    What can I do?
    jScrollPane1.remove(listCheckBox);
    jScrollPane1.remove(listDescription);
    jPanel1.revalidate();
    jPanel1.repaint();

    This is the entire code. It should compile. I don't know if this counts as a SSCCE or not. I am using the JDK 1.5 & Swing Layout Extensions 1.0 libraries. With this code, I have my jScrollPane to clear out correctly. Now, the mouselistener only works every other time the find button is clicked.
    import java.awt.Component;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.util.Vector;
    import javax.swing.JCheckBox;
    import javax.swing.JList;
    import javax.swing.ListCellRenderer;
    import javax.swing.ListSelectionModel;
    import javax.swing.UIManager;
    * NewJFrame.java
    * Created on November 3, 2006, 11:17 AM
    * @author  a1025667
    public class NewJFrame extends javax.swing.JFrame {
        /** Creates new form NewJFrame */
        public NewJFrame() {
            initComponents();
            this.jScrollPane1.requestFocus();
        /** 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() {
            jPanel1 = new javax.swing.JPanel();
            jScrollPane1 = new javax.swing.JScrollPane();
            jTextField1 = new javax.swing.JTextField();
            jButton1 = new javax.swing.JButton();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            jTextField1.addFocusListener(new java.awt.event.FocusAdapter() {
                public void focusGained(java.awt.event.FocusEvent evt) {
                    jTextField1FocusGained(evt);
            jButton1.setText("jButton1");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
            org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
            jPanel1.setLayout(jPanel1Layout);
            jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(jPanel1Layout.createSequentialGroup()
                    .add(131, 131, 131)
                    .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                        .add(jPanel1Layout.createSequentialGroup()
                            .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 188, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(14, 14, 14)
                            .add(jButton1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 87, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                        .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 306, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .addContainerGap(166, Short.MAX_VALUE))
            jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(jPanel1Layout.createSequentialGroup()
                    .add(25, 25, 25)
                    .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                        .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(jButton1))
                    .add(63, 63, 63)
                    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 147, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(117, Short.MAX_VALUE))
            org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .addContainerGap()
                    .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addContainerGap())
            layout.setVerticalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .addContainerGap()
                    .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addContainerGap())
            pack();
        }// </editor-fold>                       
        private void jTextField1FocusGained(java.awt.event.FocusEvent evt) {                                       
    // TODO add your handling code here:
            Vector listData = new Vector();
            JList emptylistCheckBox = new JList();
            JList emptylistDescription = new JList();
            emptylistCheckBox.setListData(listData);
            emptylistDescription.setListData(listData);
            jScrollPane1.setRowHeaderView(emptylistCheckBox);
            jScrollPane1.setViewportView(emptylistDescription);
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
    // TODO add your handling code here:
            Vector listData = new Vector();
            listData.add("row1");
            listData.add("row2");
            listData.add("row3");
            listCheckBox.setListData(buildCheckBoxItems(listData.size()));
            listDescription.setListData(listData);
            listCheckBox.setCellRenderer(new CheckBoxRenderer());
            listCheckBox.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            listCheckBox.addMouseListener(new MouseAdapter() {
                public void mouseClicked(MouseEvent me) {
                    int selectedIndex = listCheckBox.locationToIndex(me.getPoint());
                    if (selectedIndex < 0)
                        return;
                    CheckBoxItem item = (CheckBoxItem)listCheckBox.getModel().getElementAt(selectedIndex);
                    item.setChecked(!item.isChecked());
                    listDescription.setSelectedIndex(selectedIndex);
                    listCheckBox.repaint();
            listDescription.setFixedCellHeight(20);
            listCheckBox.setFixedCellHeight(listDescription.getFixedCellHeight());
            jScrollPane1.setRowHeaderView(listCheckBox);
            jScrollPane1.setViewportView(listDescription);
            jScrollPane1.revalidate();
            jScrollPane1.repaint();
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new NewJFrame().setVisible(true);
        private CheckBoxItem[] buildCheckBoxItems(int totalItems) {
            CheckBoxItem[] checkboxItems = new CheckBoxItem[totalItems];
            for (int counter=0;counter<totalItems;counter++) {
                checkboxItems[counter] = new CheckBoxItem();
            return checkboxItems;
        class CheckBoxItem {
            private boolean isChecked;
            public CheckBoxItem() {
                isChecked = false;
            public boolean isChecked() {
                return isChecked;
            public void setChecked(boolean value) {
                isChecked = value;
        class CheckBoxRenderer extends JCheckBox implements ListCellRenderer {
            public CheckBoxRenderer() {
                setBackground(UIManager.getColor("List.textBackground"));
                setForeground(UIManager.getColor("List.textForeground"));
            public Component getListCellRendererComponent(JList listBox, Object obj, int currentindex,
                    boolean isChecked, boolean hasFocus) {
                setSelected(((CheckBoxItem)obj).isChecked());
                return this;
        // Variables declaration - do not modify                    
        private javax.swing.JButton jButton1;
        private javax.swing.JPanel jPanel1;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JTextField jTextField1;
        // End of variables declaration                  
        public  JList listCheckBox = new JList();
        public  JList listDescription = new JList();
    }

  • Removing Data from a Database using JList

    Hi,
    I have the following JList with a "Remove" button.
    I have managed to populate the JList with entries from the DataBase but now i am having problems removing the data from the data base using the JList.
    What i am trying to achieve is, when an entry is selected from the JList and the "Remove" button is hit, the entry should be removed from the JList and from the database.
    How do i do this, 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;
        private ResultSet rs = null;
        String names = new String();
        private DefaultListModel listModel = new DefaultListModel();
        public RemoveD(Frame parent, boolean modal) {
            super(parent, modal);
            initComponents();
        private void initComponents() {
            try {
                Class.forName("com.mysql.jdbc.Driver");
            } catch (ClassNotFoundException ex) {
                ex.printStackTrace();
            try {
                String userID = "";
                String psw = "";
                String url;
                url = "jdbc:mysql://localhost:3306/mqnames";
                conn = DriverManager.getConnection(url, userID, psw);
                stat = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                        ResultSet.CONCUR_READ_ONLY);
                rs = stat.executeQuery("SELECT queueName FROM queuenametable");
                int j = 0;
                while (rs.next()) {
                    names = rs.getString(1);
                    System.out.println("rs: " + names);
                    listModel.addElement(names);
                }//end of While
                stat.close();
                conn.close();
            } catch (SQLException ex) {
                ex.printStackTrace();
            scrollPane = new JScrollPane();
            list = new JList(listModel);
            list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            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();
        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);
    }

    Ask a specific question. Do you know how to get the selected item in the list? Do you know how to write a delete query in SQL?

  • JList and ALT+MOUSE CLICK to remove item

    Hi,
    How can I create action that is fired when ALT+mouse button is pressed? This should remove item from JList that was clicked. Only thing I can think of is to create MouseAdapter and inside it check if ALT button is pressed. Any other (better) ideas?

    SSCCE
    import java.awt.Dimension;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.DefaultListModel;
    import javax.swing.JFrame;
    import javax.swing.JList;
    public class Run extends JFrame {
         public Run(){
              DefaultListModel listModel = new DefaultListModel();
              listModel.addElement("Element 1");
              listModel.addElement("Element 2");
              listModel.addElement("Element 3");
              JList list = new JList(listModel);
              list.addMouseListener(new RemoveAction(list, listModel));
              add(list);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              setPreferredSize(new Dimension(200,200));
              pack();
              setLocationRelativeTo(null);
              setVisible(true);
         public static void main(String[] args) {
              new Run();
    class RemoveAction extends MouseAdapter{
           private JList list;
           private DefaultListModel listModel;
           public RemoveAction(JList list, DefaultListModel listModel){
                this.list = list;
                this.listModel = listModel;
           public void mouseClicked(MouseEvent e){
               if(e.isAltDown()){
                   int index = list.locationToIndex(e.getPoint());
                   if(index>-1)
                        listModel.remove(index);
    }

  • Remove Selection from jList ??

    Hi,
    How do I remove a Selection from a jList??
    The items in the jList are Vectors
    I now use jList.clearSelection() but the selection stays there..
    Thanks,
    Marie

    Funny you should ask. I just now decided to try out what I suggested because I've never actually used a Vector in a JList. In my simple example below, I actually have to call repaint on the list to get it to refresh. I should NOT have to do that. Might be a bug in the VM?Please try it out on your machine and see if you can remove the 'repaint' statement in my action listener and get the list to refresh.
    I use 1.4.1_02 JDK. Let me know also which JDK you're using. Thanks!
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.BorderLayout;
    import java.util.Vector;
    public class MyList extends JFrame {
         Vector model = new Vector();
         public MyList() {
              super();
              setSize(300,400);
              getContentPane().setLayout(new BorderLayout());
              buildModel();
              final JList list = new JList(model);
              getContentPane().add(list, BorderLayout.CENTER);
              JButton btn = new JButton("remove");
              btn.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        model.remove(list.getSelectedIndex());
                        list.repaint(); //why should I have to force a repaint???
              getContentPane().add(btn, BorderLayout.NORTH);
              addWindowListener(new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                        System.exit(0);
              show();
         private void buildModel() {
              model.add("one");
              model.add("two");
              model.add("three");
         public static void main(String[] args) {
              new MyList();

  • Removing PopUp from JList

    Hi!
    I have a small problem with popup menus in a JList. When I right click on an entry in the JList, the menu is shown. However, there is possible to change the selected entry in the list with the arrowkeys and the popup menu does not dissapear then. How can I do so that the popup is hidden when I change selected value?
    Thanks in advance,
    // Andreas

    EditLurk.java [70:1] Class Javax.swing.JList not found in type declaration or import.
    adminList = new Javax.swing.JList(adminModel);
    ^
    EditLurk.java [70:1] No constructor in JList matches <init>(DefaultListModel)
    adminList = new Javax.swing.JList(adminModel);
    ^

  • Populating JList with a single database column

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

    I figured out how to do it

  • How to  move items from one JList to other

    Can u pls help me out to implement this(I m using Netbeans 5.5):
    I want to move items from one JList to other thru a ADD button placed between JLists, I am able to add element on Right side JList but as soon as compiler encounter removeElementAt() it throws Array Index Out of Bound Exception
    and if I use
    removeElement() it removes all items from left side JList and returns value false.
    Pls have a look at this code:
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
    // TODO add your handling code here:
    Object selItem = jList1.getSelectedValue();
    int selIndex = jList1.getSelectedIndex();
    DefaultListModel model = new DefaultListModel();
    jList2.setModel(model);
    model.addElement(selItem);
    DefaultListModel modelr = new DefaultListModel();
    jList1.setModel(modelr);
    flag = modelr.removeElement(selItem);
    //modelr.removeElementAt(selIndex);
    System.out.println(flag);
    }

    hi Rodney_McKay,
    Thanks for valuable time but my problem is as it is, pls have a look what I have done and what more can b done in this direction.
    Here is the code:
    import javax.swing.DefaultListModel;
    import javax.swing.JList;
    public class twoList extends javax.swing.JFrame {
    /** Creates new form twoList */
    public twoList() {
    initComponents();
    //The code shown below is automatically generated and we can�t edit this code
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
    private void initComponents() {
    jScrollPane1 = new javax.swing.JScrollPane();
    jList1 = new javax.swing.JList();
    jButton1 = new javax.swing.JButton();
    jScrollPane2 = new javax.swing.JScrollPane();
    jList2 = new javax.swing.JList();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    jList1.setModel(new javax.swing.AbstractListModel() {
    String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
    public int getSize() { return strings.length; }
    public Object getElementAt(int i) { return strings[i]; }
    jList1.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
    public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
    jList1ValueChanged(evt);
    jScrollPane1.setViewportView(jList1);
    jButton1.setText("ADD>>");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton1ActionPerformed(evt);
    jScrollPane2.setViewportView(jList2);
    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGap(31, 31, 31)
    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jButton1)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addContainerGap(78, Short.MAX_VALUE))
    layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jScrollPane1, jScrollPane2});
    layout.setVerticalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGap(62, 62, 62)
    .addComponent(jButton1))
    .addGroup(layout.createSequentialGroup()
    .addContainerGap()
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
    .addContainerGap(159, Short.MAX_VALUE))
    layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {jScrollPane1, jScrollPane2});
    pack();
    }// </editor-fold>
    //automatic code ends here
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
    // TODO add your handling code here:
            jList1 = new JList(new DefaultListModel());
            jList2 = new JList(new DefaultListModel());
             Object selItem = jList1.getSelectedValue();
             System.out.println(selItem);
            ((DefaultListModel) jList1.getModel()).removeElement(selItem);
            ((DefaultListModel) jList2.getModel()).addElement(selItem);
    //Now trying with this code it is neither adding or removing and the value �null� is coming in �selItem� .It may be bcoz JList and Jlist are already instantiated in automatic code. So, I tried this:
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
    // TODO add your handling code here:
             Object selItem = jList1.getSelectedValue();
             System.out.println(selItem);
            ((DefaultListModel) jList1.getModel()).removeElement(selItem);
            ((DefaultListModel) jList2.getModel()).addElement(selItem);
    //Now with this as soon as I click on �jButton1�, it is throwing this error:
    Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: twoList$1 cannot be cast to javax.swing.DefaultListModel
            at twoList.jButton1ActionPerformed(twoList.java:105)
            at twoList.access$100(twoList.java:13)
            at twoList$3.actionPerformed(twoList.java:50)
            at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
            at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
            at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
            at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
            at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
            at java.awt.Component.processMouseEvent(Component.java:6038)
            at javax.swing.JComponent.processMouseEvent(JComponent.java:3260)
            at java.awt.Component.processEvent(Component.java:5803)
            at java.awt.Container.processEvent(Container.java:2058)
            at java.awt.Component.dispatchEventImpl(Component.java:4410)
            at java.awt.Container.dispatchEventImpl(Container.java:2116)
            at java.awt.Component.dispatchEvent(Component.java:4240)
            at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322)
            at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3986)
            at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)
            at java.awt.Container.dispatchEventImpl(Container.java:2102)
            at java.awt.Window.dispatchEventImpl(Window.java:2429)
            at java.awt.Component.dispatchEvent(Component.java:4240)
            at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
            at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
            at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
            at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
            at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)

  • Moving stuff from one JList to an other

    Hi,
    I'm trying to develop a JPanel with two JLists and two arrow JButtons to be able to move (!) stuff from the left JList to the Right and backwards. Both JLists have a ListCellRenderer that extend JLabel.
    Managed to do a 'copy' of selected values to the other JList,
    eg.
    public void addKeyWords(java.awt.event.ActionEvent actionEvent,javax.swing.JList allKeyWords,javax.swing.JList chosenKeyWords) {
    java.util.List chosenValues = java.util.Arrays.asList(chosenKeyWords.getSelectedValues());
    java.util.List selectedValues = java.util.Arrays.asList(allKeyWords.getSelectedValues());
    java.util.Set set = new java.util.HashSet();
    set.addAll(selectedValues);
    javax.swing.JList l = new javax.swing.JList(set.toArray());
    getChosenKeyWordsList().setModel(l.getModel());
    return;
    but can't figure out how to get stuff to disappear in the first JList when it is moved to the other JList nore how to enable the user to 'add' elements one at a time.
    Enyone?

    hi.
    what i do when i want to remove from the right side list:
    //get an array of indexes that needs to be removed.
    elements[] removedItems = getStrings(rightListData, selected);
    //copy all elements that do NOT need to be removed
    rightListData = utils.copyArrayWithoutIndex(rightData, selected);
    rightList.setListData(rightListData);
    same goes for left side.
    basically, i remove all selected elements from the array of rows, and re-set the list data model.
    HTH.

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

  • Using a JList

    Hi everyone! Happy new year.
    Okay, I have some work for some keen programmer out there to do. There are 10 duke dollars avaliable to whoever can help me with this problem.
    I am using a JList to display a list of milestones which are required later on in my project. When no item is selected from the list, I want the 'Delete Milestone' button to automatically disable and when an item is selected from the list, I want it to auto enable. If the list is empty, then the button should remain disabled. For this to work I think I need some sort of ListSelectionListener but I am not sure how to do this. At the moment I get an exception whenever I click on the 'Delete Milestone' button and no selection has been made, which is understandable.
    Another thing that I need doing is that if a milestone is added to the list, and the 'Critical Milestone' is selected, then whenever that item is selected from the list, the background colour should be red; whenever a 'Non-critical Milestone' is created, then that should remain with a yellow background whenever selected from the list. At the moment, the background colour changes to whatever the last added milestone happened to be - either red or yellow for all entries that have been added to the list. If anyone can help me with this then that would be really appreciated and very helpful. The 4 files can be found below - just run the 'AddMilestoneTest' class to start the app. Thanks.
    * AddMilestoneTest.java
    * 29/12/02 (Date start)
    * This class is for iteration purposes for
    * the "Add Milestone" wizard
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    public class AddMilestoneTest extends JPanel
    private JButton addMilestoneButton;
    public JFrame addMilestoneFrame;
    static AddMilestoneTest instance;     
    public AddMilestoneTest()
         instance = this;
    // create new button
    addMilestoneButton = new JButton("Add Milestone");
    // create tooltip for every button
    addMilestoneButton.setToolTipText("Add Milestone");
    // add our button to the JPanel
    add(addMilestoneButton);
    // construct button action
    AddMilestoneListener listener1 = new AddMilestoneListener();
    // Add action listener to button
    addMilestoneButton.addActionListener(listener1);
    private class AddMilestoneListener implements ActionListener
    public void actionPerformed(ActionEvent evt)
    addMilestoneFrame = new JFrame("Add Milestone Wizard*");
    MilestoneSplitPanel milestoneSplitPanel = new MilestoneSplitPanel();
    addMilestoneFrame.getContentPane().add(milestoneSplitPanel);
    addMilestoneFrame.setSize(850, 305);
    addMilestoneFrame.setVisible(true);
    // Main entry point into the program
    public static void main(String[] args)
    // Create a frame to hold us and set its title
    JFrame frame = new JFrame("Add Milestone Iteration");
    // Set frame to close after user request
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    // Add our panel to the frame
    AddMilestoneTest amt = new AddMilestoneTest();
    frame.getContentPane().add(amt, BorderLayout.CENTER);
    // Resize the frame
    frame.setSize(680, 480);
    // Make the windows visible
    frame.setVisible(true);
    * MilestoneSplitPanel.java
    * 29/12/02
    * This class creates a split between the
    * AddMilestonePanel and the CurrentMilestonePanel
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    public class MilestoneSplitPanel extends JPanel
    // Declare a split panel
    JSplitPane splitPanel;
    // Declare the panels required here
    AddMilestonePanel addMilestonePanel;
    CurrentMilestonePanel currentMilestonePanel;
    public MilestoneSplitPanel()
    // Create the panels required
    addMilestonePanel = new AddMilestonePanel();
    currentMilestonePanel = new CurrentMilestonePanel();
    // Create the split panel with our two panels
    splitPanel = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, currentMilestonePanel, addMilestonePanel);
    splitPanel.setDividerLocation(200);
    //Provide minimum sizes for the two components in the split pane
    addMilestonePanel.setMinimumSize(new Dimension(350, 200));
    currentMilestonePanel.setMinimumSize(new Dimension(100, 100));
    //Add the split panel to this panel.
    add(splitPanel, BorderLayout.CENTER);
    * AddMilestonePanel.java
    * 29/12/02 (Date start)
    * This class is for iteration purposes for
    * the "Add Milestone" wizard
    import javax.swing.*;
    import javax.swing.border.*;
    import java.awt.*;
    import java.awt.event.*;
    public class AddMilestonePanel extends JPanel
    private JLabel milestoneNameLabel;
    private JLabel milestoneNameMaxChar;
    private JLabel milestoneECDLabel;
    private JLabel forwardSlash1;
    private JLabel forwardSlash2;
    private JLabel dateFormatLabel;
    private JLabel selectOne;
    private JTextField milestoneName;
    private JComboBox theDate;
    private JComboBox theMonth;
    private JComboBox theYear;
    private ButtonGroup group;
    private JRadioButton criticalMilestone;
    private JRadioButton nonCriticalMilestone;
    private JButton addMilestone;
    private JButton deleteMilestone;
    private JButton cancel;
    private JButton finish;
    private JList currentMilestones;
    static AddMilestonePanel instance;
    public String dateSelected;
    public String monthSelected;
    public String yearSelected;
    public AddMilestonePanel()
    instance = this;
    // create additional panels to hold objects
    JPanel topPanel = new JPanel();
    JPanel middlePanel = new JPanel();
    JPanel lowerPanel = new JPanel();
    JPanel buttonPanel = new JPanel();
    // Create a border around the "toppanel"
    Border etched = BorderFactory.createBevelBorder(BevelBorder.RAISED, Color.black, Color.blue);
    Border titled = BorderFactory.createTitledBorder(etched, "Provide a name for the milestone");
    topPanel.setBorder(titled);
    // Create a border around the "middlepanel"
    Border etched1 = BorderFactory.createBevelBorder(BevelBorder.RAISED, Color.black, Color.blue);
    Border titled1 = BorderFactory.createTitledBorder(etched1, "Enter an estimated completion date of the milestone");
    middlePanel.setBorder(titled1);
    // Create a border around the "lowerpanel"
    Border etched2 = BorderFactory.createBevelBorder(BevelBorder.RAISED, Color.black, Color.blue);
    Border titled2 = BorderFactory.createTitledBorder(etched2, "Choose whether the milestone is critical or non-critical");
    lowerPanel.setBorder(titled2);
    // initialise JLabel objects
    milestoneNameLabel = new JLabel("Milestone Name: ");
    milestoneNameMaxChar = new JLabel("(Max 20 chars)");
    milestoneECDLabel = new JLabel("Estimated Completion Date: ");
    forwardSlash1 = new JLabel("/");
    forwardSlash2 = new JLabel("/");
    dateFormatLabel = new JLabel("(Date/Month/Year)");
    selectOne = new JLabel("(Select One)");
    // create textfield for the milestone name
    milestoneName = new JTextField(20);
    milestoneName.setColumns(15);
    topPanel.validate();
    // create the combo boxes for the date
    theDate = new JComboBox(new String[]
    "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16",
    "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31"
    theDate.setEditable(false);
    theMonth = new JComboBox(new String[]
    "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"
    theMonth.setEditable(false);
    theYear = new JComboBox(new String[]
    "2001", "2002", "2003", "2004", "2005", "2006", "2007", "2008", "2009", "2010", "2011", "2012"
    theYear.setEditable(false);
    // create the radio buttons and add them to the group
    group = new ButtonGroup();
    criticalMilestone = new JRadioButton("Critical Milestone", true);
    nonCriticalMilestone = new JRadioButton("Non-critical Milestone", false);
    group.add(criticalMilestone);
    group.add(nonCriticalMilestone);
    // create the buttons
    addMilestone = new JButton("Add Milestone", new ImageIcon("D:/My Uni Work/Final Year Project/Graphics/addMilestoneIcon.JPG"));
    deleteMilestone = new JButton("Delete Milestone", new ImageIcon("D:/My Uni Work/Final Year Project/Graphics/deleteMilestone.JPG"));
    cancel = new JButton("Cancel", new ImageIcon("D:/My Uni Work/Final Year Project/Graphics/StopControl.gif"));
    finish = new JButton("Finish", new ImageIcon("D:/My Uni Work/Final Year Project/Graphics/bluearrow.gif"));
    // set tooltips for buttons
    addMilestone.setToolTipText("Add Milestone");
    deleteMilestone.setToolTipText("Delete Milestone");
    cancel.setToolTipText("Cancel");
    finish.setToolTipText("Finish");
    // set the state of the buttons when first run
    deleteMilestone.setEnabled(false);
    finish.setEnabled(false);
    // add objects to panels
    topPanel.add(milestoneNameLabel);
    topPanel.add(milestoneName);
    topPanel.add(milestoneNameMaxChar);
    middlePanel.add(milestoneECDLabel);
    middlePanel.add(theDate);
    middlePanel.add(forwardSlash1);
    middlePanel.add(theMonth);
    middlePanel.add(forwardSlash2);
    middlePanel.add(theYear);
    middlePanel.add(dateFormatLabel);
    lowerPanel.add(criticalMilestone);
    lowerPanel.add(nonCriticalMilestone);
    lowerPanel.add(selectOne);
    buttonPanel.add(addMilestone);
    buttonPanel.add(deleteMilestone);
    buttonPanel.add(cancel);
    buttonPanel.add(finish);
    // use Box layout to arrange panels
    Box hbox1 = Box.createHorizontalBox();
    hbox1.add(topPanel);
    Box hbox2 = Box.createHorizontalBox();
    hbox2.add(middlePanel);
    Box hbox3 = Box.createHorizontalBox();
    hbox3.add(lowerPanel);
    Box hbox4 = Box.createHorizontalBox();
    hbox4.add(buttonPanel);
    Box vbox = Box.createVerticalBox();
    vbox.add(hbox1);
    vbox.add(Box.createGlue());
    vbox.add(hbox2);
    vbox.add(Box.createGlue());
    vbox.add(hbox3);
    vbox.add(Box.createGlue());
    vbox.add(hbox4);
    this.add(vbox, BorderLayout.NORTH);
    // create instance of cancelButtonListener
    CancelButtonListener cancelListen = new CancelButtonListener();
    // create instance of AddMilestoneListener
    AddMilestoneListener milestoneListener = new AddMilestoneListener();
    // create instance of DeleteMilestoneListener
    DeleteMilestoneListener deleteListener = new DeleteMilestoneListener();
    // add actionListener for the buttons
    cancel.addActionListener(cancelListen);
    addMilestone.addActionListener(milestoneListener);
    deleteMilestone.addActionListener(deleteListener);
    private class CancelButtonListener implements ActionListener
    public void actionPerformed(ActionEvent event)
    Object source = event.getSource();
    if(source == cancel)
    AddMilestoneTest.instance.addMilestoneFrame.setVisible(false);
    private class AddMilestoneListener implements ActionListener
    public void actionPerformed(ActionEvent event)
    String milestoneNameText = milestoneName.getText().trim();
    int textSize = milestoneNameText.length();
    dateSelected = (String)theDate.getSelectedItem();
    monthSelected = (String)theMonth.getSelectedItem();
    yearSelected = (String)theYear.getSelectedItem();
    if(textSize > 20)
    //display a JOptionPane
    JOptionPane.showMessageDialog(AddMilestonePanel.instance, "You have entered a title that is greater than 20 characters.",
    "Text too Long", JOptionPane.ERROR_MESSAGE);
    else if(textSize == 0)
    //display a JOptionPane
    JOptionPane.showMessageDialog(AddMilestonePanel.instance, "You have not entered a milestone name. Please do so (Maximum 20 Characters).",
    "No Project Name Entered", JOptionPane.ERROR_MESSAGE);
    else if(dateSelected == "30" && monthSelected == "02" || dateSelected == "31" && monthSelected == "02" || dateSelected == "31" && monthSelected == "04" ||
    dateSelected == "31" && monthSelected == "06" || dateSelected == "31" && monthSelected == "09" || dateSelected == "31" && monthSelected == "11")
    JOptionPane.showMessageDialog(AddMilestonePanel.instance, "You have selected an invalid date. Re-check that the date is valid.",
    "Invalid Date Selected", JOptionPane.ERROR_MESSAGE);
    } // ANOTHER CHECK IS REQUIRED HERE WHEN INTEGRATING - IF DATE ENETERED IS WITHIN THE START DATE AND END DATE OF THE PROJECT
    else
    deleteMilestone.setEnabled(true);
    finish.setEnabled(true);
    if(criticalMilestone.isSelected())
    CurrentMilestonePanel.instance.listModel.addElement(milestoneNameText);
    CurrentMilestonePanel.instance.currentMilestoneList.setSelectionBackground(Color.red);
    else if(nonCriticalMilestone.isSelected())
    CurrentMilestonePanel.instance.listModel.addElement(milestoneNameText);
    CurrentMilestonePanel.instance.currentMilestoneList.setSelectionBackground(Color.yellow);
    private class DeleteMilestoneListener implements ActionListener
    public void actionPerformed(ActionEvent event)
    if(CurrentMilestonePanel.instance.listModel.size() > 0)
    int selectedItemIndex = CurrentMilestonePanel.instance.currentMilestoneList.getSelectedIndex();
    CurrentMilestonePanel.instance.listModel.remove(selectedItemIndex);
    * CurrentMilestonePanel.java
    * 29/12/02 (Date start)
    * This class is for iteration purposes for
    * the "Add Milestone" wizard
    import javax.swing.*;
    import javax.swing.border.*;
    import java.awt.*;
    import java.awt.event.*;
    public class CurrentMilestonePanel extends JPanel
    public JList currentMilestoneList;
    private JLabel currentMilestonesAdded;
    // List Model that will hold the data for the list
    public DefaultListModel listModel;
    // Scroll pane that will contain the list
    private JScrollPane scrollPaneList;
    static CurrentMilestonePanel instance;
    // Constructor
    public CurrentMilestonePanel()
    instance = this;
    // create label
    currentMilestonesAdded = new JLabel("Current Milestones Added");
    listModel = new DefaultListModel();
    //listModel.addElement("No Milestones Added");
    // Create the list
    currentMilestoneList = new JList(listModel);
    // Set single selection, and select the first item
    currentMilestoneList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    currentMilestoneList.setSelectedIndex(0);
    // Create a scroll panel to hold list
    scrollPaneList = new JScrollPane(currentMilestoneList);
    // Set the preferred size
    scrollPaneList.setPreferredSize(new Dimension(130, 200));
    //Add the scroll pane to this panel.
    add(currentMilestonesAdded, BorderLayout.NORTH);
    add(scrollPaneList, BorderLayout.CENTER);

    I suggest that you look into the swing tutorial. There are some samples of how to write ListSelectionListener.
    I quickly scanned your code for the DeleteMilestoneListener. You get an exception here because you don't check if an item is selected in the list.

  • Removing a window and adding a new one with swing.

    Hi,
    A friend of mine recently asked me to add a GUI for a small chat he made, so I thought I'd help him out. I've come across something that's troubled me in the past, and I could never find a solution. What I'm trying to do is make it so a log in window pops up (have that working alright) and then when you press sign in, it removes that window (log in) and adds the main chat window (have this fully functional, too).
    If someone could provide an example or point me in the direction of the proper API to look into, so that I don't have to look through them all, I'd be extremely grateful.
    Here's an SSCCE example:
    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import javax.swing.DefaultListModel;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JList;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextField;
    import javax.swing.JTextPane;
    import javax.swing.ListSelectionModel;
    import javax.swing.ScrollPaneConstants;
    import javax.swing.SwingUtilities;
    public class Gui extends JFrame {
         public static final DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
         public String sessionId;
         public int returnCode;
         public boolean recievedReturnCode;
         public boolean errorConnecting;
         public long lastActionDelay;
         private JScrollPane listScrollPane;
         private JList list;
         private JTextPane console;
         private JButton signInButton;
         private JScrollPane consoleScrollPane;
         private JTextField typingField;
         private DefaultListModel userList;
         private JButton sendButton;
         public static void main(String[] args) {
              try {
                   SwingUtilities.invokeAndWait(new Runnable() {
                        public void run() {
                             new Gui().setVisible(true);
              } catch (Exception e) {
                   e.printStackTrace();
         public Gui() {
              setResizable(false);
              setSize(500, 500);
              consoleScrollPane = new JScrollPane();
              console = new JTextPane();
              typingField = new JTextField();
              userList = new DefaultListModel();
              sendButton = new JButton();
              initializeLoginWindow();
              setDefaultCloseOperation(EXIT_ON_CLOSE);
         public void initializeLoginWindow() {
              setTitle("Login");
              signInButton = new JButton("Sign in");
              signInButton.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent evt) {
                        initializeChatWindow();
              signInButton.setBounds(5, 100, 75, 20);
              getContentPane().add(signInButton);
              getContentPane().setLayout(new BorderLayout());
              getContentPane().add(new JPanel());
         public void initializeChatWindow() {
              consoleScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
              consoleScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
              consoleScrollPane.setViewportView(console);
              consoleScrollPane.setBounds(5, 5, 575, 350);
              console.setEditable(false);
              typingField.setEditable(true);
              typingField.setBounds(5, 360, 575, 25);
              list = new JList(userList);
            list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            list.setSelectedIndex(0);
            list.setVisibleRowCount(5);
            listScrollPane = new JScrollPane(list);
              listScrollPane.setBounds(585, 5, 110, 350);
              sendButton.setText("Send");
              sendButton.setBounds(585, 360, 111, 25);
              getContentPane().add(consoleScrollPane);
              getContentPane().add(typingField);
              getContentPane().add(listScrollPane);
              getContentPane().add(sendButton);
              getContentPane().setLayout(new BorderLayout());
              getContentPane().add(new JPanel());
    }Thanks in advanced!

    jduprez wrote:
    I've come across something that's troubled me in the past, and I could never find a solutionWhat is the problem?
    a log in window pops up (have that working alright)
    and then when you press sign in, it removes that window (log in) and adds the main chat window (have this fully functional, too).Hum, between what is working alright and what is already functional, I fail to see what is missing. Again, what is your problem/question?
    If someone could provide an example or point me in the direction of the proper API to look into, so that I don't have to look through them all, I'd be extremely grateful.
    [url http://download.oracle.com/javase/tutorial/uiswing/components/frame.html]JFrames and [url http://download.oracle.com/javase/tutorial/uiswing/components/dialog.html]dialogs seem to show enough API usage to do that. Still, I stronlgy encourage you to read the whole Swing tutorial: http://download.oracle.com/javase/tutorial/uiswing/index.html
    Incase you didn't see the hyperlink above, here's the SSCCE link: http://www.mediafire.com/?e5e3ci3kbvickla
    The "S" in SSCCE stands for "Short" (or, depending on authors, "Simple"). Anyway, a decent SSCCE should fit within a forum post (between code tags please). The whole idea is to provide the simplest thing to people willing to help. No doubtful sites. No non-standard extensions.
    Best regards,
    The problem is that I cannot seem to remove the first pane, leaving the second one to be drawn on the current one.
    In reguards to SSCCE, I always thought it was just a short runnable class example, but I've added the class to the main post. I'll take a look at the API in a few as well.

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

Maybe you are looking for

  • XML data contains linebreaks in the tags - won't work with Flash

    Hello. I have a Flash file that draws upon an xml file for content. When I try to create that xml file using an Adobe Designer 7.0 pdf form, I get line breaks in the tags. You don't see them in Internet Explorer XML viewer but you do see them in Note

  • Help Scripting "Mirror displays" and resolution

    HI there, I work in a situation where it would be super helpful to have a script that runs at login that sets the resolution to a specific resolution and even more awesome if the script could make them "mirror displays" as well. Any help would be so

  • Home Sharing stopped working

    I've been using home sharing on my Ipad 2 and Apple TV for almost a year now with no problem. 2 weeks ago I did the most recent update and now home sharing doesn't work. It'll work for maybe 4 mins right after I start up Itunes, but then it will just

  • Inserting PIP video into captivate demo - audio problems

    Hello, I am using CP6 and have captured a 1 second demo then imported an FLV file into the demo as a PIP file.  It works fine except for some reason it has chopped 1.7 seconds off of the audio at the beginning of the demo: Any help would greatly be a

  • Mitigation text is missing / critical permission can't mitigated

    Hello together, I have problems with the mitigation tasks in CUP after a risk analysis. Installation: SP14.1 If I want mitigate the risk (SoD), the mitigation ID will be show but not the text (short or long) of the mitigation. Is this a bug in CUP? A