简体   繁体   中英

How to get Jlist with JScrollpane list to show on a JFrame? isn't appear

I'm working on a school assignment with a GUI application dealing with a bookstorage system, the application should display a list of the book in bookstorage but when I launch it nothing shows. Below I will post the code I'm working with. Also I can only change or add new code in the TODO tagged areas. From my understanding the book array is stored in the bookarraymodel, which the jlist contains and thats within the jscrollpane which is added to the contentpane, so it should display it.

here we have the book class:

/**
 * Book
 */
public class Book {

    public enum BookCategory {
        Programming, Database, Design
    }

    private String title;
    private String authors;
    private int pages;
    private BookCategory category;

    public Book(String title, String authors, int pages, BookCategory category) {
        this.title = title;
        this.authors = authors;
        this.pages = pages;
        this.category = category;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getAuthors() {
        return authors;
    }

    public void setAuthors(String authors) {
        this.authors = authors;
    }

    public int getPages() {
        return pages;
    }

    public void setPages(int pages) {
        this.pages = pages;
    }

    public BookCategory getCategory() {
        return category;
    }

    public void setCategory(BookCategory category) {
        this.category = category;
    }
}

next is the bookarraymodel were using to help manage the book array:

import javax.swing.AbstractListModel;

/**
 * A book array model used by {@link javax.swing.JList}.
 */
public class BookArrayModel extends AbstractListModel<String> {
    private Book[] bookArray;

    public BookArrayModel(Book[] bookArray) {
        this.bookArray = bookArray;
    }

    public void setBookArray(Book[] bookArray) {
        this.bookArray = bookArray;
    }

    @Override
    public int getSize() {
        return bookArray.length;
    }

    @Override
    public String getElementAt(int index) {
        return bookArray[index].getTitle();
    }
}

then we have the bookstorage class that has the book array stored and various methods to help manage it:

/**
 * A collection of {@link Book}.
 */
public class BookStorage {

    private Book[] books = new Book[100];

    public BookStorage() {

    }

    /**
     * Initializes the book storage with some arbitrary book objects.
     */
    public void initBooks() {
        // TODO Add your code here...
        books[0] = new Book("Testing book1", "Jamal", 420, Book.BookCategory.Programming );
        books[1] = new Book("Effective Java", "Joshua Bloch",344,Book.BookCategory.Design);
        books[2]= new Book("Clean Code", "Robert C. Martin",780, Book.BookCategory.Programming);
        books[3] = new Book("Java Concurrency in Practice", "Brian Goetz", 256, Book.BookCategory.Database);
        books[4] = new Book("Head First Design Patterns", "Kathy Sierra", 588, Book.BookCategory.Database);
        books[5]= new Book("Spring in Action", "Criag Walls", 533,Book.BookCategory.Programming);
        books[6] = new Book("Test Driven", "Lasse Koskela",434,Book.BookCategory.Design);
        books[7] = new Book("The Definitive Guide to Java Performance", "Scott Oaks",567,Book.BookCategory.Database );
        books[8] = new Book("Head First Java", "Bert Bates",923,Book.BookCategory.Design );
        books[9] = new Book("Head First Object-Oriented Analysis and Design", "David West",844,Book.BookCategory.Programming);
        books[10] = new Book("Java: A Beginner's Guide", "Herbert Schildt", 255,Book.BookCategory.Programming);




    }


    /**
     * Uses the given book to update the existing book with the same title.
     */
    public void update(Book book) {
        // TODO Add your code here...

    }

    /**
     * Removes a book by title.
     */
    public void remove(String bookTitle) {
        // TODO Add your code here...

    }

    /**
     * Adds a new book.
     */
    public void add(Book book) {
        // TODO Add your code here

    }

    /**
     * Gets a book by title.
     */
    public Book getByTitle(String title) {
        // TODO Add your code here...
   }

    /**
     * Searches for books whose title contains the keyword and returns them ordered by titles (in alphabet order).
     */
    public Book[] titleSearch(String keyword) {
        // TODO Add your code here...

        }


    /**
     * Returns all books sorted by their titles (in alphabet order).
     */
    public Book[] getAll() {
        // TODO Add your code here...
        sortByTitle(books);
        return books;


    }

    /**
     * Sorts an array of books by their titles in alphabet order.
     */
    private Book[] sortByTitle(Book[] bookArray) {
        // TODO Add your code here...
        Book temp;
        for(int i = 1; i < bookArray.length; i++)
        {
          for(int j = i; j > 0; j--)
          {
            if(bookArray[j] == null)
            {
              break;
            }
          else if(bookArray[j].getTitle().charAt(0) <bookArray[j-1].getTitle().charAt(0))
          {
            temp = bookArray[j];
            bookArray[j] = bookArray[j-1];
            bookArray[j=1] = temp;
          }
        }
      }


        return bookArray;
    }

}

finally is the booklistwindow that launches the app, it sets up the GUI:

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.awt.*;

/**
 * BookListWindow
 */
public class BookListWindow extends JFrame implements ActionListener {

    //======== Top ========
    private JPanel topPanel;
    private JTextField searchTextField;
    private JButton searchButton;
    private JButton clearButton;

    //======== Middle ========
    private JScrollPane titleListScrollPane;
    private JList<String> bookTitleList;

    //======== Bottom ========
    private JPanel bottomPanel;
    private JButton addButton;
    private JButton detailButton;
    private JButton removeButton;

    //======== Data ========
    private BookStorage bookStorage;
    private BookArrayModel bookListModel;

    public BookListWindow(BookStorage bookStorage) {
        this.bookStorage = bookStorage;
        bookListModel = new BookArrayModel(bookStorage.getAll());
        initComponents();
    }


  //  / * Clears the search results and list all the books.
     //*/
    public void resetToAll() {
        bookListModel.setBookArray(bookStorage.getAll());
        searchTextField.setText("");
        bookTitleList.updateUI();
    }

    /**
     * Returns the book storage.
     */
    public BookStorage getBookStorage() {
        return bookStorage;
    }

    /**
     * Initializes the components.
     */
    private void initComponents() {
        Container contentPane = getContentPane();
        this.setTitle("Book Management");
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        //======== Top ========
        topPanel = new JPanel();
        searchTextField = new JTextField();
        searchButton = new JButton("SEARCH");
        clearButton = new JButton("CLEAR");

        searchButton.addActionListener(this);
        clearButton.addActionListener(this);

        {
            // Set the layout for topPanel and add the buttons.
            // TODO Add your code here...
            topPanel.setLayout(new GridLayout(1,3));
            topPanel.add(searchTextField);
            topPanel.add(searchButton);
            topPanel.add(clearButton);
        }


        //======== Middle ========
        titleListScrollPane = new JScrollPane();
        bookTitleList = new JList<>();

        {
            // Configure the bookTitleList 1) Use single selection
            //TODO Add your code here...

            bookTitleList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        }

        titleListScrollPane.setViewportView(bookTitleList);

        //======== Bottom ========
        bottomPanel = new JPanel();
        addButton = new JButton("ADD");
        detailButton = new JButton("DETAIL");
        removeButton = new JButton("REMOVE");

        addButton.addActionListener(this);
        detailButton.addActionListener(this);
        removeButton.addActionListener(this);

        {
            // Set the layout for bottomPanel and add the buttons.
            // TODO Add your code here...
            bottomPanel.setLayout(new GridLayout(1,3));
            bottomPanel.add(addButton);
            bottomPanel.add(detailButton);
            bottomPanel.add(removeButton);


        }

        contentPane.setLayout(new BorderLayout());
        {
            // Add the components to contentPane with proper layout options.
            // TODO Add your code here...

          contentPane.add(topPanel, BorderLayout.NORTH);
          contentPane.add(titleListScrollPane, BorderLayout.CENTER);
          contentPane.add(bottomPanel, BorderLayout.SOUTH);


        }

        pack();
        setLocationRelativeTo(getOwner());
    }

    @Override
    public void actionPerformed(ActionEvent e) {
       if (e.getSource() == searchButton) {
           // Action for the SEARCH button
           // TODO Add your code here...



       } else if (e.getSource() == clearButton) {
           // Action for the CLEAR button
           // TODO Add your code here...
           resetToAll();

       } else if (e.getSource() == addButton) {
           // Action for the ADD button
           // TODO Add your code here...


       } else if (e.getSource() == detailButton) {
           // Action for the DETAIL button
           // TODO Add your code here...


       } else if (e.getSource() == removeButton) {
           // Action for the REMOVE button
           if (!bookTitleList.isSelectionEmpty()) {
               bookStorage.remove(bookTitleList.getSelectedValue());
               JOptionPane.showMessageDialog(this, "Remove Successful!");
               resetToAll();
           }
       }
    }

    public static void main(String[] args) {
        BookStorage bookStore = new BookStorage();
        bookStore.initBooks();
        BookListWindow bookListWindow = new BookListWindow(bookStore);
        bookListWindow.setVisible(true);
    }
}

The only problem which does not let the JFrame to show up, is that this code does not compile. If you implement the methods getByTitle and titleSearch of BookStorage (to return something useful), then the code will compile and the frame will show up (I tested it). Now what is left is to implement all the methods of the assignment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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