0

Я работаю над своей лабораторной задачей.Добавление экземпляра объекта в массив в следующем доступном месте

Создайте класс Book (String ISBN, строковое название, intprice) Обеспечить параметризированный конструктор Обеспечить toStringmethod Обеспечить методы геттер Дизайн графический интерфейс на левой На нажатие кнопки добавления, новый экземпляр книги создается с указанные данные и добавляются в массив в следующем доступном месте. Предоставить функциональность для следующих и предыдущих кнопок для итерации по массиву и отображения соответствующей записи в полях

У меня возникла проблема с внедрением кнопки add и next с использованием arraylist и итератора списка. Я написал для этого код, но он не работает соответственно.

Вот мой код ниже Он содержит два класса

**BookGUI.java** 
/* 
* To change this license header, choose License Headers in Project Properties. 
* To change this template file, choose Tools | Templates 
* and open the template in the editor. 
*/ 
package ahmed.classtask.one; 

import java.awt.GridBagConstraints; 
import java.awt.GridBagLayout; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.util.ArrayList; 
import java.util.ListIterator; 
import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JOptionPane; 
import javax.swing.JTextField; 

/** 
* 
* @author Ahmed Adnan 
*/ 
public class BookGUI extends JFrame { 

    public static void main(String args[]) { 
     BookGUI b = new BookGUI(); 
     b.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     b.setVisible(true); 
     b.setSize(300, 200); 
     b.setTitle("Book Frame"); 

    } 

    private JFrame f; 
    //private JPanel p; 

    private JLabel l1; 
    private JLabel l2; 
    private JLabel l3; 

    private JTextField t1; 
    private JTextField t2; 
    private JTextField t3; 

    private JButton addButton; 
    private JButton nextButton; 
    private JButton previousButton; 

    public BookGUI() { 
     frame(); 

    } 

    public final void frame() { 

     setLayout(new GridBagLayout()); 
     GridBagConstraints c = new GridBagConstraints(); 

     l1 = new JLabel("ISBN"); 
     c.fill = GridBagConstraints.HORIZONTAL; 
     c.gridx = 0; 
     c.gridy = 0; 
     add(l1, c); 

     t1 = new JTextField(10); 
     c.fill = GridBagConstraints.HORIZONTAL; 
     c.gridx = 1; 
     c.gridy = 0; 
     c.gridwidth = 3; 
     add(t1, c); 

     l2 = new JLabel("Title"); 
     c.fill = GridBagConstraints.HORIZONTAL; 
     c.gridx = 0; 
     c.gridy = 1; 
     c.gridwidth = 1; 
     add(l2, c); 

     t2 = new JTextField(10); 
     c.fill = GridBagConstraints.HORIZONTAL; 
     c.gridx = 1; 
     c.gridy = 1; 
     c.gridwidth = 3; 
     add(t2, c); 

     l3 = new JLabel("Price"); 
     c.fill = GridBagConstraints.HORIZONTAL; 
     c.gridx = 0; 
     c.gridy = 2; 
     c.gridwidth = 2; 
     add(l3, c); 

     t3 = new JTextField(10); 
     c.fill = GridBagConstraints.HORIZONTAL; 
     c.gridx = 1; 
     c.gridy = 2; 
     c.gridwidth = 3; 
     add(t3, c); 

     addButton = new JButton("Add"); 
     c.fill = GridBagConstraints.HORIZONTAL; 
     c.gridx = 0; 
     c.gridy = 3; 
     c.gridwidth = 1; 
     add(addButton, c); 

     nextButton = new JButton("Next"); 
     c.fill = GridBagConstraints.HORIZONTAL; 
     c.gridx = 1; 
     c.gridy = 3; 
     add(nextButton, c); 

     previousButton = new JButton("Previous"); 
     c.fill = GridBagConstraints.HORIZONTAL; 
     c.gridx = 2; 
     c.gridy = 3; 
     add(previousButton, c); 

     MyListener listener = new MyListener(); 

     addButton.addActionListener(listener); 
     nextButton.addActionListener(listener); 
     previousButton.addActionListener(listener); 

    } 

    private class MyListener implements ActionListener { 

     @Override 
     public void actionPerformed(ActionEvent e) { 
      String isbnTF, titleTF; 
      int priceTF = 0; 

      ArrayList<Book> book = new ArrayList<>(); 
      ListIterator itr = book.listIterator(); 

      Book b = null; 

      Object op = e.getSource(); 

      if (op.equals(addButton)) { 
       isbnTF = t1.getText(); 
       titleTF = t2.getText(); 

       try { 
        priceTF = Integer.parseInt(t3.getText()); 

       } catch (Exception ex) { 
        JOptionPane.showMessageDialog(null, "Invalid input! "); 

       } 

       b = new Book(isbnTF, titleTF, priceTF); 

       book.add(b); 
       t1.setText(""); 
       t2.setText(""); 
       t3.setText(""); 

       System.out.println(b); 
      } else if (op.equals(nextButton)) { 

     if (itr == null) { 
      itr = book.listIterator(); 
     } 
     System.out.print("reached here"); 
     if (itr.hasNext()) { 

      b = (Book) itr.next(); 
      t1.setText(b.getIsbn()); 
      t2.setText(b.getTitle()); 
      t3.setText(b.getPrice()+" "); 
     } 

      } 

     } 


    } 

} 

Книга Класс

/* 
* To change this license header, choose License Headers in Project Properties. 
* To change this template file, choose Tools | Templates 
* and open the template in the editor. 
*/ 
package ahmed.classtask.one; 

/** 
* 
* @author Ahmed Adnan 
*/ 
public class Book { 

    private String isbn; 
    private String title; 
    private int price; 

    public Book(String isbn, String title, int price) { 
     this.isbn = isbn; 
     this.title = title; 
     this.price = price; 
    } 

    /** 
    * @return the isbn 
    */ 
    public String getIsbn() { 
     return isbn; 
    } 

    /** 
    * @return the title 
    */ 
    public String getTitle() { 
     return title; 
    } 

    /** 
    * @return the price 
    */ 
    public int getPrice() { 
     return price; 
    } 

    @Override 
    public String toString() { 
     return "Book{" + "isbn=" + isbn + ", title=" + title + ", price=" +  price + '}'; 
    } 



} 
+0

Пожалуйста, пост только соответствующий код. – Masudul

+0

Проблема в действии слушателя класса ^^ в BookGUI классе –

ответ

0

Вы создаете book объект внутри actionPerformed(...), что означает, что каждый раз, когда вы нажимаете кнопку, которую вы начинаете с новой, пустой ArrayList<Book>.

Вы должны сделать объект book переменной класса.

Например:

private class MyListener implements ActionListener { 
    ArrayList<Book> book = new ArrayList<>(); 
    int displayedBook = 0; 
    @Override 
    public void actionPerformed(ActionEvent e) { 
     String isbnTF, titleTF; 
     int priceTF = 0; 
     Book b = null; 
     Object op = e.getSource(); 
     if (op.equals(addButton)) { 
      isbnTF = t1.getText(); 
      titleTF = t2.getText(); 
      try { 
       priceTF = Integer.parseInt(t3.getText()); 
      } catch (Exception ex) { 
       JOptionPane.showMessageDialog(null, "Invalid input! "); 
      } 
      b = new Book(isbnTF, titleTF, priceTF); 
      book.add(b); 
      t1.setText(""); 
      t2.setText(""); 
      t3.setText(""); 
      System.out.println(b); 
     } else if (op.equals(nextButton)) { 
      if(book.size()>0){ 
       if(displayedBook >= book.size()){ 
        displayedBook = 0; 
       } 
       b = book.get(displayedBook); 
       t1.setText(b.getIsbn()); 
       t2.setText(b.getTitle()); 
       t3.setText(b.getPrice()+" "); 
       displayedBook++; 
      } 
     } 
    } 
} 
} 
+0

Большое спасибо. Теперь его решение –

 Смежные вопросы

  • Нет связанных вопросов^_^