我想用代碼填充我的列表選擇監聽器方法,但我不知道如何處理它。從本質上講,我希望當從JList中選擇一個項目時,該方法可以填充多個文本字段。需要與列表選擇監聽器的幫助
我JList的是這樣的:
private JList <String> contactList;
private DefaultListModel<String> model;
//Textfields
comboBookType = new JComboBox(BookType.values());
nameText = new JTextField("", 17);
authorText = new JTextField("", 17);
genreText = new JTextField ("", 17);
comboCategory = new JComboBox (readCategory());
//initialize defaultlistmodel and jlist
model = new DefaultListModel <String>();
bookList = new JList (model);
bookList.setVisibleRowCount(10);
bookList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
bookList.setFixedCellHeight (20);
bookList.setFixedCellWidth (130);
bookList.setBorder (BorderFactory.createLineBorder(Color.BLACK,1));
JPanel left = new JPanel(new BorderLayout());
left.add (new JScrollPane(bookList), BorderLayout.NORTH);
bookList.addListSelectionListener (new ListSelection());
//populating Jlist
class openFileListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
book.getBooks();
for (String name : addressBook.getBooks())
{
model.addElement(name);
}
}
}
//the getBooks() method in my Library class
public ArrayList<String> getBooks()
{
File file;
Scanner input;
BookType type;
ArrayList<String> books;
ArrayList<String> names = new ArrayList<String>();
try
{
file = new File ("Books.txt");
input = new Scanner (file);
while (input.hasNext())
{
String line = input.nextLine ();
String [] book = line.split(",");
type = BookType.valueOf(info[0]);
String name = book[1];
b = new Book (type, book[1], book[2], book[3], book[4], info[5]);
list.add (b);
information.add (name);
numOfBooks++;
}
input.close ();
}
catch (FileNotFoundException e)
{
JOptionPane.showMessageDialog (null, "File not found");
}
return information;
}
這裏是我到目前爲止我的列表中選擇偵聽器:
private class ListSelection implements ListSelectionListener
{
public void valueChanged (ListSelectionEvent e)
{
book.getInfo ();
int index = bookList.getSelectedIndex ();
}
//getInfo() method in Library class
public ArrayList<Book> getInfo()
{
File file;
Scanner input;
BookType type;
ArrayList<String> book;
try
{
file = new File ("Book.txt");
input = new Scanner (file);
while (input.hasNext())
{
String line = input.nextLine ();
String [] info = line.split(",");
type = BookType.valueOf(info[0]);
String name = info[1];
Book b = new Contact (type, info[1], info[2], info[3], info[4],info[5]);
list.add (b);
}
input.close ();
}
catch (FileNotFoundException e)
{
JOptionPane.showMessageDialog (null, "File not found");
}
return list;
這不是很多,但我有從哪裏去沒轍這裏。我知道我必須利用從getSelectedIndex
得到的index
,但我不知道如何,請幫助,謝謝。
請勿使用「代碼段」標籤。選擇你的代碼並使用'{}'按鈕。 – camickr
@camickr謝謝,我從現在開始做。只是好奇,爲什麼我會在「代碼片段」上使用'{}'? – lamps