【问题标题】:Java List MVC PatternJava 列表 MVC 模式
【发布时间】:2010-12-16 04:15:38
【问题描述】:

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

谢谢。

【问题讨论】:

    标签: java model-view-controller swing


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      有几种创建列表模型的方法,讨论了here。 Swing 使用可分离的模型架构,在A Swing Architecture Overview 中有进一步描述。

      【讨论】:

        猜你喜欢
        • 2010-12-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-02
        • 1970-01-01
        • 2018-07-19
        相关资源
        最近更新 更多