我在使用MVC模式在Java语言中实现JList时遇到了一些问题,因为我不知道如何编写控制器和视图(每一个都在单独的类中),以便从model.Example调用方法:在模型中,我有一个名为( getBooks() )的方法,在图形用户界面中有一个带有JList的框架,这样当我单击列表中的一项时,一些文本框将填充适当的信息(标题、作者等)。问题是我不确定如何在控制器和/或view.By中编写侦听器,而列表中的项也应该从模型中加载。
谢谢。
发布于 2010-12-15 06:40:53
您要向JList注册的侦听器是一个ListSelectionListener,它会在选择发生更改时向您发出警报。如果我这样做,我会做类似以下的事情:
public class BookListModel {
public List<Book> getBooks() {
// Replace with however you get your books
return Arrays.asList(new Book("It", "Stephen King"),
new Book("The Lion, The Witch, and the Wardrobe", "C.S. Lewis"));
}
}
public class Book {
private String title;
private String author;
public String getTitle() { return title; }
public String getAuthor() { return author; }
public Book(String title, String author) {
this.title = title;
this.author = author;
}
}
public class BookListView extends JPanel {
private JList books;
private BookInfoView bookInfo;
private BookListModel model;
public BookListView(BookListModel model) {
books = new JList(model.toArray());
bookInfo = new BookInfoView();
books.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
// get the book that was clicked
// call setBook on the BookInfoView
}
});
// Add the JList and the info view
}
}
public class BookInfoView extends JPanel {
private JLabel titleLabel;
private JLabel authorLabel;
private JTextField titleTextField;
private JTextField authorTextField;
public void setBook(Book b) {
// adjust the text fields appropriately
}
}上面假设图书列表是静态的。如果不是这样,您应该让BookListModel扩展DefaultListModel并填充适当的方法。
发布于 2010-12-15 04:02:11
有几种创建列表模型的方法,讨论了here。Swing使用可分离的模型体系结构,在中对此进行了进一步描述。
https://stackoverflow.com/questions/4442120
复制相似问题