2010-12-14 73 views
1

我在使用MVC模式在Java中實現JList時遇到了一些麻煩,因爲我無法弄清楚我該如何編寫控制器和視圖(每個在separte類中),以便我可以調用模型中的方法。示例:在模型中,我有一個名爲(getBooks())的方法,在GUI中有一個帶有JList的框架,這樣當我單擊列表中的某個項目時,一些文本框會被填充適當的信息(標題,作者等)。問題是我不知道如何在控制器和/或視圖中編寫監聽器。順便說一下,列表中的項目也應該從模型中加載。Java列表MVC模式

謝謝。

回答

2

您想要向您的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並填寫適當的方法。