+
+ /**
+ * The number of books in this group.
+ *
+ * @return the count
+ */
+ public int getBooksCount() {
+ return books.size();
+ }
+
+ /**
+ * Return the index of the currently selected book if any, -1 if none.
+ *
+ * @return the index or -1
+ */
+ public int getSelectedBookIndex() {
+ int index = -1;
+ for (int i = 0; i < books.size(); i++) {
+ if (books.get(i).isSelected()) {
+ index = i;
+ break;
+ }
+ }
+ return index;
+ }
+
+ /**
+ * Select the given book, or unselect all items.
+ *
+ * @param index
+ * the index of the book to select, can be outside the bounds
+ * (either all the items will be unselected or the first or last
+ * book will then be selected, see <tt>forceRange></tt>)
+ * @param forceRange
+ * TRUE to constraint the index to the first/last element, FALSE
+ * to unselect when outside the range
+ */
+ public void setSelectedBook(int index, boolean forceRange) {
+ int previousIndex = getSelectedBookIndex();
+
+ if (index >= books.size()) {
+ if (forceRange) {
+ index = books.size() - 1;
+ } else {
+ index = -1;
+ }
+ }
+
+ if (index < 0 && forceRange) {
+ index = 0;
+ }
+
+ if (previousIndex >= 0) {
+ books.get(previousIndex).setSelected(false);
+ }
+
+ if (index >= 0 && !books.isEmpty()) {
+ books.get(index).setSelected(true);
+ }
+ }
+
+ /**
+ * The action to execute when a key is typed.
+ *
+ * @param e
+ * the key event
+ */
+ private void onKeyTyped(KeyEvent e) {
+ boolean consumed = false;
+ boolean action = e.getKeyChar() == '\n';
+ boolean popup = e.getKeyChar() == ' ';
+ if (action || popup) {
+ consumed = true;
+
+ int index = getSelectedBookIndex();
+ if (index >= 0) {
+ GuiReaderBook book = books.get(index);
+ if (action) {
+ book.action();
+ } else if (popup) {
+ book.popup(book, book.getWidth() / 2, book.getHeight() / 2);
+ }
+ }
+ }
+
+ if (consumed) {
+ e.consume();
+ }
+ }
+
+ /**
+ * The action to execute when a key is pressed.
+ *
+ * @param e
+ * the key event
+ */
+ private void onKeyPressed(KeyEvent e) {
+ boolean consumed = false;
+ if (e.isActionKey()) {
+ int offset = 0;
+ switch (e.getKeyCode()) {
+ case KeyEvent.VK_LEFT:
+ offset = -1;
+ break;
+ case KeyEvent.VK_RIGHT:
+ offset = 1;
+ break;
+ case KeyEvent.VK_UP:
+ offset = -itemsPerLine;
+ break;
+ case KeyEvent.VK_DOWN:
+ offset = itemsPerLine;
+ break;
+ }
+
+ if (offset != 0) {
+ consumed = true;
+
+ int previousIndex = getSelectedBookIndex();
+ if (previousIndex >= 0) {
+ setSelectedBook(previousIndex + offset, true);
+ }
+ }
+ }
+
+ if (consumed) {
+ e.consume();
+ }
+ }
+
+ @Override
+ public void paint(Graphics g) {
+ super.paint(g);
+
+ Rectangle clip = g.getClipBounds();
+ if (clip.getWidth() <= 0 || clip.getHeight() <= 0) {
+ return;
+ }
+
+ if (!isEnabled()) {
+ g.setColor(new Color(128, 128, 128, 128));
+ g.fillRect(clip.x, clip.y, clip.width, clip.height);
+ }
+ }