Jlist

I would like to know how can I add the content of a JTextField to a Vector, that will display in a JList.
THX

I need to be able to display an empty list and them using a JTextField, the user will add the name that he wants and press add to add to the list..
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.*;
* <p>Title: </p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Company: </p>
* @author not attributable
* @version 1.0
public class NumberGUI extends JFrame {
  public NumberGUI() {
    getContentPane().setLayout(new BorderLayout());
    Vector v = new Vector();
    v.addElement("20");
    v.addElement("-5");
    v.addElement("10");
    Collections.sort(v);
    final JList list = new JList(v);
    getContentPane().add(new JScrollPane(list));
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(200,300);
  public static void main(String[] args) {
    new NumberGUI().show();
}

Similar Messages

  • How t print out selected values from a Jlist

    hi iam trying to get the selected values from a list to print out as a string but iam getting ,Invalid cast from java.lang.Object[] to java.lang.String.is there any way to get the selected values t print ut as a string?? import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class MultipleSelection2 extends JFrame {
    private JList colorList, copyList;
    private JButton copy;
    private String colorNames[] =
    { "Black", "Blue", "Cyan", "Dark Gray", "Gray",
    "Green", "Light Gray", "Magenta", "Orange", "Pink",
    "Red", "White", "Yellow" };
    public MultipleSelection2()
    super( "Multiple Selection Lists" );
    Container c = getContentPane();
    c.setLayout( new FlowLayout() );
    colorList = new JList( colorNames );
    colorList.setVisibleRowCount( 5 );
    colorList.setFixedCellHeight( 15 );
    colorList.setSelectionMode(
    ListSelectionModel.MULTIPLE_INTERVAL_SELECTION );
    c.add( new JScrollPane( colorList ) );
    // create copy button
    copy = new JButton( "Copy >>>" );
    copy.addActionListener(
    new ActionListener() {
    public void actionPerformed( ActionEvent e )
    // place selected values in copyList
    copyList.setListData(
    colorList.getSelectedValues());
    String s1 =(String)colorList.getSelectedValues();

    Since the JList method 'getSelectedValues' returns an object array you'll need to iterate through the array and cast each object in the array to a string as you access them.
    Object[] o = colorList.getSelectedValues();
    for(int count=0,end=o.length; count<end; count++) {
    String s = (String) o[count];
    Hope that helps
    Talden

  • Getting all the values from a JList

    Hi,
    I want to get all the values from a JList and store it into an array. Any method is available to perform this task? Pls help me out with this task.

    Use getModel() on the list to get the ListModel and then call getSize() and getElementAt(int) to loop over the elements
    HTH
    Mike

  • I want to insert some checkboxes in a JList

    ...is it possible?
    I tried, but it inserts a string!
    This is my code:
    JList list = new JList();
    panel.add(list);
    CheckBox check = new JCheckBox("Yes");
    DefaultListModel model = new DefaultListModel();
    model.addElement(check);
    list.setModel(model);
    // I am able to see only the String "javax.swing.JCheckBox[,0,0,0x0, invalid,alignmentX=0.0,alignmentY=0.5,border=javax.swing.plaf.BorderUIResource$CompoundBorder.....text=User Prefix]"
    Thank you!

    Hi Sorin,
    you can aquire your data in a loop and use shift registers to store your data (use an array). To get the maximum of the array there is a function in labview "Array Max & Min".
    Hope this helps.
    Mike

  • How to center JList  items

    Hi,
    I want to center my Jlist item instead of leave them in the left like usual. My List contains pictures and for the beauty of the design it's better to have the image in the center of each cells. How to do it?
    thanks.

    Do you know how to make a JLabel which contains a centred icon? Now make a ListCellRenderer that uses one of those to render your images in the JList.

  • How to save JList items!

    hello,
    i m creating a class that has three JList components.
    My problem is how to save the each JList items into a seperate logfile(ie. text file).

    More info required:
    What are in the JList? Strings? Custom objects?
    Do you know basic file IO?
    http://java.sun.com/docs/books/tutorial/essential/io/index.html
    What you will need to do is get the model, ilterate over each element, then write that element out. If the element is a string, then that is easy, just create a FileWriter, and write the string, followed by a new line.
    If it is a custom object, then the task is harder, and you need to decide how that object should be represented.
    If you are after a computer readable view of the model, rather than a human readable, which can easily be read by Java back into a ListModel, then you want to look at XMLEncoder and XMLDecode, or the Serializing Objects tutorial.
    http://java.sun.com/docs/books/tutorial/uiswing/components/list.html

  • 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 print text from Textfield onto JList?

    Hi!I've typed a sentence on the textfield,and wat can i do to print out this sentence onto the JList i've created,after clicking on my JButton"Post".And on the JList,there must be numbering for each sentence.And New sentences will directly be added after the previous sentence.Hope to get a quick reply from any helpful people.Thanks.

    This should do it. (Typed straight in so untested).
    // create components and event listener
    JTextField textField = new JTextField();
    final DefaultListModel listModel = new DefaultListModel();
    JList list = new JList(listModel);
    JButton button = new JButton("Add");
    button.addActionListener(new ActionListener()
        public void actionPerformed(ActionEvent ev)
            String text = textField.getText();
            listModel.add(text);
    // now display them

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

  • How do i add a Scroll Bar to a  JList Component using absolute positioning?

    I've got a applet whose content pane is set to null. I've create a jlist component on this applet and using absolute positioning set the bounds at
    ListBox1.setBounds(380,10, 500, 500);.
    My problem is creating add a scroll bar to the list box.
    JScrollPane scrollPane = new JScrollPane(ListBox1);
    C.add(scrollPane);
    The above code is what i use and when i run this applet i don't see the list box at all. How do i add a scrollbar to this list box or JList component. Please help.

    You need to setBounds() on the JScrollPane, not the JList.
    The JScrollPane is the component that is being added to the panel.

  • How to add words from a JTextField to a JList

    Im working on my final project for Java programming class using JApplet.
    Im trying to create a spelling test/wordfind
    I want to be able to have the user type a word in the JtextField press the "Add" button (Jbutton) and have the word be added to the JList.
    then click the "Start" Button and have the all the words from the JList be put in random stops in a panel and fill around all the words with random letters.
    then when the user clicks on the letter of the words they are finding it will change colors if they click on it again it will change back to its original color.
    So far I have my layout set up its adding the proper Listeners and events to achieve the desired results.
    I know this is way more advanced than what My Instructor is even teacher but I am very interested in Java and want to learn a lot more about it.
    If anyone has suggestions or know where i can find the information Im looking for please let me know.
    Thanks
    Code I have so Far:
    * @(#)SpellingTest.java
    * SpellingTest Applet application
    * @author
    * @version 1.00 2010/11/10
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class SpellingTest extends JApplet implements ActionListener {
         Image img;
         ImageIcon icon;
         private Image title;
         JTextField word;
         JButton addWord;
         JLabel label;
         JList wordList;
         public void init() {//opening init
                   getContentPane().setLayout(null);
                   getContentPane().setBackground(Color.WHITE);
                   title = getImage(getDocumentBase(), "title.jpg");
                   //The text field
                   word = new JTextField();
                   word.setLocation(190,100);
                   word.setSize(85,30);
                   getContentPane().add(word);
                   word.addActionListener(this);
                   //The addWord button
                   addWord = new JButton("ADD");
                   addWord.setLocation(295, 100);
                   addWord.setSize(90,30);
                   getContentPane().add(addWord);
                   addWord.setBackground(new Color(146, 205, 220));
                   addWord.addActionListener(this);
                   //The label
                   label = new JLabel("Type your spelling words:");
                   label.setLocation(25, 65);
                   label.setSize(250,100);
                   getContentPane().add(label);
                   label.setForeground(new Color(146, 205, 220));
                   //The List
                   wordList = new JList();
                   JScrollPane scrollPane = new JScrollPane(wordList,
                   ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
                   ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
                   scrollPane.setLocation(25,150);
                   scrollPane.setSize(150,300);
                   getContentPane().add(scrollPane);
         }//closing init
         public void actionPerformed (ActionEvent ae){
              Object obj = ae.getSource();
              String text = word.getText();
              if (obj == addWord){
                   if (text.length()>0);
                   wordList.addString("");
         public void paint(Graphics g) {
              super.paint(g);
    }

    Read the first posting titled "Welcome to the new home" to learn how to use code tags. Then you can edit your posting so the code is formatted and readable.
    I want to be able to have the user type a word in the JtextField press the "Add" button (Jbutton) and have the word be added to the JList.Read the JList API and follow the link to the Swing tutoral on "How to Use Lists" where you will find a working example.
    So far I have my layout Actually you haven't. You should learn how to use layout managers. Again the Swing tutorial explains what layout managers are and provides working example of using them.
    I am very interested in Java and want to learn a lot more about it.A great place to start is by read tutorials because they always contain working example. Here are some [url http://download.oracle.com/javase/tutorial/]Java tutorrial.

  • 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.

  • How do i pass selected value of JList in one frame to other frame?

    hai everybody,
    In my application where i m using swing as GUI in that i require selected value of Jlist in one frame to other frame ..
    Since i need the previous frame jlist selected value for my application.
    How this can be done
    Help me pa
    Thanx in advance

    You need to post your Short, Self-Contained, Compilable Example or SSCCE if you need further help.

  • Using an embedded driver instead of client, and refreshing JList

    I am finishing up a simple database interface program that I need to do in order to graduate. There are a couple issues I need to address.
    1. This program is meant to be on one computer with one connection to a database. Currently, when I build the program and run the .jar file, it will not work unless I have manually started the server in Netbeans. Once the server is on, it works like a champ. But since I have to send this to my professor it must work without him doing any additional setup. For this I figured I could use the embeddedDriver, but unfortantely I cant get that to work.
    In netbeans I can right click on the main database icon and select "New Connection" and i have the option of choosing the embedded driver yet when i put the database name in and the user and password it gives me the
    error: "Unable to add connection. Cannot establish a connection to jdbc:derby:MaxxTrax using org.apache.derby.jdbc.EmbeddedDriver (Database 'MaxxTrax' not found).
    Why is it that I can use the client driver without a problem yet not the embedded one? And if I cant use the embedded one, how can I set up the client driver so it will automatically start the server (does the end user need to have the server installed or will the clean and build do that)?
    2. Using the netbeans gui builder, i created a jList that I bound to my database's name query. I then have multiple textFields that i bound to whatever jList selection there is and tell it to update with the specified data. My problem is, that I cannot get the jList to "refresh". Right now when I add somebody to the database it visually writes over another persons record, but doesn't actually delete record. So if i could just figure out how to make it look at the database again I could do it automatically after entering in a new record. I've tried nameList.validate(), updateUI() and even tried to copy the ide generated code that actually binds the data but no go.
    Once I get these two little things taken care of I am done!! Please help, its greatly appreciated.

    I'm not getting much help out there.....anyone??
    I need to make the database seem invisible to the end user application.
    When I try to use an embedded driver I keep getting errors. In netbeans, I can see the "Java DB(Embedded)" link under drivers, and when I hit connect using.. I input all the correct data and it gives me the following error:
    Error: Unable to add connection. Cannot establish a connection to jdbc:derby:MaxxTrax using org.apache.derby.jdbc.EmbeddedDriver (Database 'MaxxTrax' not found).
    Under the Database setting the pointer for the java db installation and database location are correct. Why can't I connect using the embedded driver, cause using that would make my life so much easier for a single application.

Maybe you are looking for