开发者

Java List MVC Pattern

I'm having some trouble implementing a JLis开发者_如何学编程t in Java using the MVC Pattern because I can't figure out how am I suppose to write the controller and the view(each one in a separte class) so that I can call the methods from the model.Example : In the model I have a method called ( getBooks() ) and in the GUI a frame with a JList so that when I click an item in the list some textboxes will get filled with the appropriate information(title, author etc). The problem is I'm not sure how to write the listeners in the controller and/or in the view.By the way the items from the list should also be loaded from the model.

Thank you.


The listener you want to register with your JList is a ListSelectionListener, which will alert you when the selection changes. If I were doing this I would do something similar to the following:

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
    }

}

The above assumes that the list of books is static. If that's not the case, you should make your BookListModel extend DefaultListModel and fill in the appropriate methods.


There are several approaches to creating a list model, discussed here. Swing uses a separable model architecture, described further in A Swing Architecture Overview.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜