繁体   English   中英

Java清单MVC模式

[英]Java List MVC Pattern

我在使用MVC模式在Java中实现JList时遇到了一些麻烦,因为我无法弄清楚我应该如何编写控制器和视图(每个都在separte类中),以便可以从中调用方法。模型。示例:在模型中,我有一个名为(getBooks())的方法,在GUI中有一个带有JList的框架,因此当我单击列表中的项目时,某些文本框将充满相应的信息(标题,作者等) )。 问题是我不确定如何在控制器和/或视图中编写侦听器,也应从模型中加载列表中的项目。

谢谢。

要在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并填写适当的方法。

有几种创建列表模型的方法,在此进行讨论。 Swing使用可分离的模型体系结构 ,在《 Swing体系结构概述》进一步描述。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM