使用javax.swing输入信息并将其存储在Array List中

时间:2014-03-19 19:06:16

标签: java swing button arraylist joptionpane

您好我正在制作一个项目,从文件中读取书籍列表,我想添加按钮按下时添加新书的可能性。但是我收到很多错误。看看我的代码:

public class Biblioteka {

    public static void main(String[] args) {

        JFrame frame = new JFrame("Biblioteka");
        frame.setVisible(true);
        frame.setSize(400, 400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel panel = new JPanel();
        frame.add(panel);
        GridBagConstraints c = new GridBagConstraints();

        JButton button = new JButton("Print List");
        JButton button2 = new JButton("Add book");

        c.gridx = 0;
        c.gridy = 0;
        c.insets = new Insets(10, 10, 10, 10);

        panel.add(button);
        panel.add(button2);

        final List<Book> listofbooks = new ArrayList<>();

        try {
            File file = new File("newfile.txt");
            Scanner input = new Scanner(file);
            while (input.hasNextLine()) {
                String input1 = input.nextLine();// read one line
                String num[] = input1.split("\\|");// split line by "|"
                int howMuch = Integer.parseInt(num[2]);
                Book k1 = new Book(num[0], num[1], howMuch);

                listofbooks.add(k1);
            }
        } catch (FileNotFoundException nf) {
            System.err.format("File does not exist");
        }

        final JLabel labelis = new JLabel();
        for (Book book : listofbooks) {

            labelis.setText("<html> "
                    + labelis.getText()
                    + "<br> Name: " + book.getName()
                    + " Tile: " + book.getTitle()
                    + " Number of books: "
                    + book.getHowMany()
            );

        }
        labelis.setText(labelis.getText() + "</html>");
        button.addActionListener(new Action() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JFrame frame2 = new JFrame("Clicked");
                frame2.setVisible(true);
                frame2.setSize(400, 300);
                JPanel panelis = new JPanel();
                panelis.add(labelis);
                frame2.add(panelis);
            }
        });

当我想要添加新书时,程序崩溃了:

        button2.addActionListener(new Action() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String knygAutorius = JOptionPane.showInputDialog("Input author: ");
                String knygPav = JOptionPane.showInputDialog("Input title: ");
                int knygKiek = Integer.parseInt(JOptionPane.showInputDialog("How many books do you want to add: "));
                int i = 0;
                for (Book book : listofbooks) {
                    if ((book.getTitle().equals(knygPav)) && (book.getName().equals(knygAutorius))) {
                        int kiekis = book.getHowMany();
                        kiekis = kiekis + knygKiek;
                        Book k2 = new Book(knygAutorius, knygPav, kiekis);
                        listofbooks.set(i, k2);
                    } else {
                        Book nauja = new Book(knygAutorius, knygPav, knygKiek);
                        listofbooks.add(nauja);
                    }
                    i++;

                }
            }
        });

    }

    static class Action implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {

        }
    }
}

我有一本课本:

public class Book {

    String name;
    String bookTitle;
    int howMany;

    public Book(String name, String bookTitle, int howMany) {
        this.name = name;
        this.bookTitle = bookTitle;
        this.howMany = howMany;
    }

    public String getName() {
        return this.name;
    }

    public String getTitle() {
        return this.bookTitle;
    }

    public int getHowMany() {
        return this.howMany;
    }

}

您可以尝试编译我的代码并查看问题。也许你可以帮助我。 错误:

Exception in thread "AWT-EventQueue-0" java.util.ConcurrentModificationException
    at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:859)
    at java.util.ArrayList$Itr.next(ArrayList.java:831)
    at biblioteka.Biblioteka$2.actionPerformed(Biblioteka.java:83)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    at java.awt.Component.processMouseEvent(Component.java:6505)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3320)
    at java.awt.Component.processEvent(Component.java:6270)
    at java.awt.Container.processEvent(Container.java:2229)
    at java.awt.Component.dispatchEventImpl(Component.java:4861)
    at java.awt.Container.dispatchEventImpl(Container.java:2287)
    at java.awt.Component.dispatchEvent(Component.java:4687)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
    at java.awt.Container.dispatchEventImpl(Container.java:2273)
    at java.awt.Window.dispatchEventImpl(Window.java:2719)
    at java.awt.Component.dispatchEvent(Component.java:4687)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:735)
    at java.awt.EventQueue.access$200(EventQueue.java:103)
    at java.awt.EventQueue$3.run(EventQueue.java:694)
    at java.awt.EventQueue$3.run(EventQueue.java:692)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
    at java.awt.EventQueue$4.run(EventQueue.java:708)
    at java.awt.EventQueue$4.run(EventQueue.java:706)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:705)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)

1 个答案:

答案 0 :(得分:1)

知道了,为什么你得到上面的错误是你要在该列表中添加一本新书并再次在for循环中调用相同的列表,因为这样你就得到了

**java.util.ConcurrentModificationException**


import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import java.io.File;
import java.io.FileNotFoundException;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;


public class Biblioteka {

    public static void main(String[] args) {

        JFrame frame = new JFrame("Biblioteka");
        frame.setVisible(true);
        frame.setSize(400, 400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel panel = new JPanel();
        frame.add(panel);
        GridBagConstraints c = new GridBagConstraints();

        JButton button = new JButton("Print List");
        JButton button2 = new JButton("Add book");

        c.gridx = 0;
        c.gridy = 0;
        c.insets = new Insets(10, 10, 10, 10);

        panel.add(button);
        panel.add(button2);

        final List<Book> listofbooks = new ArrayList<Book>();

        try {
            File file = new File("d:\\a.txt");
            Scanner input = new Scanner(file);
            while (input.hasNextLine()) {
                String input1 = input.nextLine();// read one line
                String num[] = input1.split(" ");// split line by "|"
                int howMuch = Integer.parseInt(num[2]);
                client.Book k1 = new client.Book(num[0], num[1], howMuch);

                listofbooks.add(k1);
            }
        } catch (FileNotFoundException nf) {
            System.err.format("File does not exist");
        }

        final JLabel labelis = new JLabel();



        button.addActionListener(new Action() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JFrame frame2 = new JFrame("Clicked");
                frame2.setVisible(true);
                frame2.setSize(400, 300);
                JPanel panelis = new JPanel();

                panelis.add(labelis);
                    //Moving for loop inside,so latest update on the books will be printed
                    //This is the reason you are not getting the modified count before
                    for (Book book : listofbooks) {

                        labelis.setText("<html> "
                                + labelis.getText()
                                + "<br> Name: " + book.getName()
                                + " Tile: " + book.getTitle()
                                + " Number of books: "
                                + book.getHowMany()
                        ); 
                }

                labelis.setText(labelis.getText() + "</html>");
                frame2.add(panelis);

            }
        });



        button2.addActionListener(new Action() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String knygAutorius = JOptionPane.showInputDialog("Input author: ");
                String knygPav = JOptionPane.showInputDialog("Input title: ");
                int knygKiek = Integer.parseInt(JOptionPane.showInputDialog("How many books do you want to add: "));
                int i = 0;
                for (Book book : listofbooks) {
                    if ((book.getTitle().equals(knygPav)) && (book.getName().equals(knygAutorius))) {
                        int kiekis = book.getHowMany();
                        kiekis = kiekis + knygKiek;
                        book.setHowMany(kiekis);
                        break;
                    } 
                    i++;
                }

                if(listofbooks.size()==i){
                     Book nauja = new Book(knygAutorius, knygPav, knygKiek);
                     listofbooks.add(nauja);
                }
            }
        });

    }

    static class Action implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {

        }
    }


}

Book.java中的小修改来设置书籍数量

public class Book {

    String name;
    String bookTitle;
    int howMany;

    public Book(String name, String bookTitle, int howMany) {
        this.name = name;
        this.bookTitle = bookTitle;
        this.howMany = howMany;
    }

    public String getName() {
        return this.name;
    }

    public String getTitle() {
        return this.bookTitle;
    }

    public int getHowMany() {
        return this.howMany;
    }
    //to set the total books
    public void setHowMany(int total){
        howMany=total;
    }

}