Results 1 to 2 of 2
Thread: searching within a JList
- 03-09-2008, 11:03 PM #1
Member
- Join Date
- Jan 2008
- Posts
- 16
- Rep Power
- 0
searching within a JList
hello, I have a bunch of empty textfiles i am using to represent as songs to test a music player im working on for an assignment. basically i use my open button to allow the user to search directories, and i select the folder with all these textfiles. all of the artists are shown in a JList. I have a textfield with the button search beside it, I want to allow the user to type in an artist, and have my program search for the artist within the JList and find it. how can I do this??
- 03-10-2008, 01:12 AM #2Java Code:
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class SearchTest { JList list; JLabel label; private void search(String text) { DefaultListModel model = (DefaultListModel)list.getModel(); // Case–sensitive. if(model.contains(text)) { int index = model.indexOf(text); list.setSelectedIndex(index); label.setText(text + " found at index " + index); } else { list.clearSelection(); label.setText(text + " not found"); } } private JScrollPane getListComponent() { String[] items = { "Bob", "Ted", "Carol", "Alice" }; DefaultListModel model = new DefaultListModel(); for(int j = 0; j < items.length; j++) model.add(j, items[j]); list = new JList(model); return new JScrollPane(list); } private JPanel getFirst() { final JTextField textField = new JTextField(12); JButton button = new JButton("Search"); ActionListener al = new ActionListener() { public void actionPerformed(ActionEvent e) { String text = textField.getText(); search(text); } }; textField.addActionListener(al); button.addActionListener(al); JPanel panel = new JPanel(); panel.add(textField); panel.add(button); return panel; } private JLabel getLabel() { label = new JLabel(); label.setHorizontalAlignment(JLabel.CENTER); Dimension d = label.getPreferredSize(); d.height = 25; label.setPreferredSize(d); return label; } public static void main(String[] args) { SearchTest test = new SearchTest(); JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.add(test.getListComponent()); f.add(test.getFirst(), "First"); f.add(test.getLabel(), "Last"); f.setSize(360,240); f.setLocation(200,200); f.setVisible(true); } }
Similar Threads
-
JList problem
By zizou147 in forum Advanced JavaReplies: 1Last Post: 04-17-2008, 09:50 AM -
searching
By nalinda in forum New To JavaReplies: 3Last Post: 12-06-2007, 03:56 AM -
Dialog and JList Doubts
By hemanthjava in forum AWT / SwingReplies: 0Last Post: 12-05-2007, 09:42 PM -
Help with JList
By Albert in forum NetBeansReplies: 1Last Post: 07-13-2007, 04:42 PM -
add a jlist column
By Alan in forum JCreatorReplies: 1Last Post: 05-28-2007, 05:51 AM
Bookmarks