使用javax.swing输入信息并将其存储在数组列表中

使用javax.swing输入信息并将其存储在数组列表中,java,swing,button,arraylist,joptionpane,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

嗨,我正在做一个项目,从文件中读取一个书籍列表,我想添加的可能性,以添加新的书籍时,按钮被按下。但是我犯了很多错误。看看我的代码:

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);
            }
        });
我有一本教科书:

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;
    }

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


明白了,为什么你会得到上面的错误是你在列表中添加了一本新书,并且再次在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) {

        }
    }


}

请张贴您的errors@VinceEmigh编辑我的帖子。看一看,我试过运行它,但没有出现任何错误。尽管您的
for(Book Book:listofbooks)
从未触发(里面有书吗?)。好像你在循环之前没有把书加进去。是的,有书。我将(Book Book:listofbooks)的循环
更改为
for(int I=0;iYeah,我的一个朋友通过更改循环就修复了相同的错误。不过,由于这是ConcurrentMode异常,我必须指出,您没有在EDT上处理任何UI。您应该查看
SwingUtilities.invokeLater()
调用EANDWAIT()
了解如何处理Swing组件。有一个线程运行您的代码,但也有一个专门用于Swing事件的线程,称为事件分派线程。我强烈建议您研究一下。只是想知道,
listofbooks
不同步,循环也不同步,我认为循环无法获取对象的lo如果我错了,请纠正我,但是如果一个线程试图影响一个对象,而另一个线程拥有锁,那么不会抛出
ConcurrentModEx
?线程与此无关。如果列表在结构上被修改(通常是添加或删除),ArrayList迭代器会抛出此异常在迭代过程中,除了迭代器自己的add/remove方法之外,任何其他方法都可以使用。@RKC如果我添加具有相同作者和标题的书籍,它将不起作用。它只会在列表的末尾添加一本新书,但不会增加这些书籍的数量。我编辑了我的文章。请检查。您的代码中几乎没有其他错误。
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)
**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) {

        }
    }


}
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;
    }

}