gpt4 book ai didi

Java 列表 MVC 模式

转载 作者:行者123 更新时间:2023-11-29 06:17:44 25 4
gpt4 key购买 nike

我在使用 MVC 模式在 Java 中实现 JList 时遇到了一些麻烦,因为我无法弄清楚我应该如何编写 Controller 和 View (每个都在一个单独的类中)以便我可以调用来自 model.Example 的方法:在模型中,我有一个名为( getBooks() )的方法,在 GUI 中有一个带有 JList 的框架,这样当我单击列表中的一个项目时,一些文本框将填充适当的信息(标题、作者等)。问题是我不确定如何在 Controller 和/或 View 中编写监听器。顺便说一下,列表中的项目也应该从模型中加载。

谢谢。

最佳答案

您要向 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并填写相应的方法。

关于Java 列表 MVC 模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4442120/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com