首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java List MVC模式

Java List MVC模式
EN

Stack Overflow用户
提问于 2010-12-15 01:26:07
回答 2查看 2.4K关注 0票数 1

我在使用MVC模式在Java语言中实现JList时遇到了一些问题,因为我不知道如何编写控制器和视图(每一个都在单独的类中),以便从model.Example调用方法:在模型中,我有一个名为( getBooks() )的方法,在图形用户界面中有一个带有JList的框架,这样当我单击列表中的一项时,一些文本框将填充适当的信息(标题、作者等)。问题是我不确定如何在控制器和/或view.By中编写侦听器,而列表中的项也应该从模型中加载。

谢谢。

EN

回答 2

Stack Overflow用户

发布于 2010-12-15 06:40:53

您要向JList注册的侦听器是一个ListSelectionListener,它会在选择发生更改时向您发出警报。如果我这样做,我会做类似以下的事情:

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2010-12-15 04:02:11

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4442120

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档