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

标签 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)

最佳答案

明白了,为什么您收到上述错误是您正在向该列表添加一本新书,并再次在 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;
    }

}

关于java - 使用javax.swing输入信息并将其存储在Array List中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22515814/

相关文章:

c# - 分布式系统中的依赖注入(inject)

java - 计算大数据集的词频

java - 从 com.symantec.itools.javax.swing 包中替换 ButtonGroupPanel

java - 错误 : Failed to resolve: com. google.girebase :firebase-core:16. 2.0

java - 已经扩展任何其他类的类可以通过任何方式扩展或实现 SwingWorker

java - 如何使用单个删除按钮从不同的 JTable 中删除行

javascript - 如何在单击按钮时加载图像?

javascript - HTML5 Canvas 上的多个事件监听器

ios - MapKit:如何使用 .xib 文件上的按钮创建自定义注释 View ?

java - ListView 不显示 - Android 工作室