如何将特定数据字段从 ArrayList 加载到某些 JTextFields?

Posted

技术标签:

【中文标题】如何将特定数据字段从 ArrayList 加载到某些 JTextFields?【英文标题】:How to load specific fields of data from an ArrayList to certain JTextFields? 【发布时间】:2021-11-16 07:51:34 【问题描述】:

我正在处理一项要求我们将数据从 .csv 文件加载到 ArrayList 的任务。 .csv 文件的第一列包含船名,必须放在JComboBox 中。当用户从JComboBox点击特定的船时,该船的相应信息将显示在JTextFields中。这是我们在方法名称itemStateChanged 中给出的算法:

    从下拉列表的选项中提取船名。 为存储完整数据的船舶列表中的每艘船舶重复。 如果船名与所选船名相同 用船舶信息填写所有文本字段 退出重复 如果结束 结束重复

到目前为止,我已经能够将数据从 .csv 文件加载到 ArrayList。我也能够完成算法的第 1 步。我不知道如何为每艘船重复此操作(步骤 2)。我也不知道如何用所选船的相应数据填写文本字段。

这是我对JTextFields 的实例化:

public class ShipGUI extends JFrame
    private int win_width = 650;
    private int win_Height = 240;
    
    private int gridRows = 3;
    private int gridCols = 2;
    JComboBox SelectShipBox;
    JTextField nameText = new JTextField();
    JTextField flagText = new JTextField();
    JTextField yearText = new JTextField();
    JTextField beamText = new JTextField();
    JTextField draftText = new JTextField();
    JTextField lengthText = new JTextField();

到目前为止,这是我的 itemStateChanged 方法的代码:

SelectShipBox = new JComboBox();
SelectShipBox.addItemListener(new ItemListener()
    public void itemStateChanged(ItemEvent ie) 
        String select = (String)ie.getItem();
    );
        
String[] templist = "Green Acres Afloat","Supnik","Her Majesty's Glory","Sulaco",
                     "Nostromos", "Flying Dutchmen", "Enterprize", "Black Peral", 
                     "PT109", "Titanic", "IronSides", "Nautilus","El Vaquero","Machu 
                      Picchu Skiff", "Folgers Best";
SelectShipBox.setModel(new javax.swing.DefaultComboBoxModel<>(templist));

在这篇文章中附上了一张最终输出应该是什么样子的图片。

编辑

这是 .csv 文件包含的数据:

Supnik,Russia,1911,64,16,38
Her Majesty's Glory,UK,1945,117,29,68
Sulaco,USA,1975,45,11,31
Nostromos,USA,1914,194,49,101
Flying Dutchmen,Tortuga,1912,69,17,36
Enterprize,USSF,1997,125,31,65
Black Peral,Barbados,1925,196,49,106
PT109,USN,1933,151,38,77
Titanic,UK,1995,188,47,97
IronSides,USA,1907,126,32,69
Nautilus,no flag,1886,127,32,68
El Vaquero,Argentina,1986,91,23,51
Machu Picchu Skiff,Peru,2004,135,34,76
Folgers Best,Columbia,1959,197,49,108

【问题讨论】:

是的,对应的信息来自.csv文件。能否请您告诉我如何在 itemStateChanged 方法中检查事件是否为 SELECT 事件? Edit 您的问题并发布包含名为 Sulaco 的船舶数据的 CSV 文件中的行。另外,我建议您访问此网页:docs.oracle.com/javase/tutorial/uiswing/index.html 我已编辑并发布了 .csv 文件包含的所有内容。我会检查页面。 【参考方案1】:

首先,您需要一个类来存储一艘船的数据。

public class ShipInfo 
    private String shipName;
    private String countryOfRegistration;
    private int yearOfConstruction;
    private int lengthAtWaterline;
    private int draftAtWaterline;
    private int beamAtWaterline;

    public ShipInfo(String name,
                    String country,
                    int year,
                    int length,
                    int draft,
                    int beam) 
        setShipName(name);
        setCountryOfRegistration(country);
        setYearOfConstruction(year);
        setLengthAtWaterline(length);
        setDraftAtWaterline(draft);
        setBeamAtWaterline(beam);
    

    public String getShipName() 
        return shipName;
    

    public String getCountryOfRegistration() 
        return countryOfRegistration;
    

    public int getYearOfConstruction() 
        return yearOfConstruction;
    

    public int getLengthAtWaterline() 
        return lengthAtWaterline;
    

    public int getDraftAtWaterline() 
        return draftAtWaterline;
    

    public int getBeamAtWaterline() 
        return beamAtWaterline;
    

    public void setShipName(String name) 
        if (name != null  &&  !name.isEmpty()) 
            shipName = name;
        
        else 
            throw new IllegalArgumentException("Null or empty ship name.");
        
    

    public void setCountryOfRegistration(String country) 
        if (country != null  &&  !country.isEmpty()) 
            countryOfRegistration = country;
        
        else 
            throw new IllegalArgumentException("Null or empty country of registration.");
        
    

    public void setYearOfConstruction(int year) 
        if (year > 0) 
            yearOfConstruction = year;
        
        else 
            throw new IllegalArgumentException("Negative year of construction.");
        
    

    public void setLengthAtWaterline(int length) 
        if (length > 0) 
            lengthAtWaterline = length;
        
        else 
            throw new IllegalArgumentException("Negative length at waterline.");
        
    

    public void setDraftAtWaterline(int draft) 
        if (draft > 0) 
            draftAtWaterline = draft;
        
        else 
            throw new IllegalArgumentException("Negative draft at waterline.");
        
    

    public void setBeamAtWaterline(int beam) 
        if (beam > 0) 
            beamAtWaterline = beam;
        
        else 
            throw new IllegalArgumentException("Negative beam at waterline.");
        
    

    public boolean equals(Object obj) 
        boolean isEqual = false;
        if (obj instanceof ShipInfo) 
            ShipInfo otherShip = (ShipInfo) obj;
            isEqual = shipName.equals(otherShip.shipName)  &&
                      countryOfRegistration.equals(otherShip.countryOfRegistration)  &&
                      yearOfConstruction == otherShip.yearOfConstruction;
        
        return isEqual;
    

    public int hashCode() 
        return shipName.hashCode() + countryOfRegistration.hashCode() + yearOfConstruction;
    

    public String toString() 
        return shipName;
    

ShipInfo 类为每个单独的数据包含一个数据成员。 equalshashCode 方法对于您的 GUI 应用程序来说并不是真正必需的,但是 toString 方法是因为 JComboBox 调用该方法来显示其项目列表以及所选项目。因此方法toString 只返回船名。

这是 GUI 应用程序代码。 (代码后的注释。)

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import javax.swing.BorderFactory;
import javax.swing.DefaultComboBoxModel;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class ShipsGui implements ActionListener, ItemListener 
    private static final String  ADD_SHIP = "Add Ship";
    private static final String  CLEAR = "Clear";
    private static final String  QUIT = "Quit";

    private JComboBox<ShipInfo> shipsCombo;
    private JFrame  frame;
    JTextField  beamText;
    JTextField  draftText;
    JTextField  flagText;
    JTextField  lengthText;
    JTextField  nameText;
    JTextField  yearText;

    @Override // java.awt.event.ActionListener
    public void actionPerformed(ActionEvent actionEvent) 
        String actionCommand = actionEvent.getActionCommand();
        switch (actionCommand) 
            case ADD_SHIP:
                JOptionPane.showMessageDialog(frame,
                                              "Not yet implemented.",
                                              actionCommand,
                                              JOptionPane.INFORMATION_MESSAGE);
                break;
            case CLEAR:
                clearAll();
                break;
            case QUIT:
                System.exit(0);
            default:
                JOptionPane.showMessageDialog(frame,
                                              actionCommand,
                                              "Unhandled",
                                              JOptionPane.WARNING_MESSAGE);
        
    

    @Override // java.awt.event.ItemListener
    public void itemStateChanged(ItemEvent itemEvent) 
        if (itemEvent.getStateChange() == ItemEvent.SELECTED) 
            Object obj = itemEvent.getItem();
            if (obj instanceof ShipInfo) 
                ShipInfo shipInfo = (ShipInfo) obj;
                nameText.setText(shipInfo.getShipName());
                flagText.setText(shipInfo.getCountryOfRegistration());
                beamText.setText(getIntText(shipInfo.getBeamAtWaterline()));
                draftText.setText(getIntText(shipInfo.getDraftAtWaterline()));
                lengthText.setText(getIntText(shipInfo.getLengthAtWaterline()));
                yearText.setText(getIntText(shipInfo.getYearOfConstruction()));
            
        
    

    private void addColumnSpacer(JPanel form, GridBagConstraints gbc) 
        addLabelToForm(form, "                    ", gbc);
    

    private void addLabelToForm(JPanel form, String text, GridBagConstraints gbc) 
        JLabel label = new JLabel(text);
        int anchor = gbc.anchor;
        gbc.anchor = GridBagConstraints.LINE_END;
        form.add(label, gbc);
        gbc.anchor = anchor;
    

    private void clearAll() 
        shipsCombo.setSelectedIndex(-1);
        beamText.setText("");
        draftText.setText("");
        flagText.setText("");
        lengthText.setText("");
        nameText.setText("");
        yearText.setText("");
    

    private void createAndDisplayGui() throws IOException 
        frame = new JFrame("Shipping News");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(createHeader(), BorderLayout.PAGE_START);
        frame.add(createForm(), BorderLayout.CENTER);
        frame.add(createButtonsPanel(), BorderLayout.PAGE_END);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
        shipsCombo.setSelectedIndex(0);
    

    private JButton createButton(String text) 
        JButton button = new JButton(text);
        button.addActionListener(this);
        return button;
    

    private JPanel createButtonsPanel() 
        JPanel buttonsPanel = new JPanel();
        buttonsPanel.add(createButton(CLEAR));
        buttonsPanel.add(createButton(QUIT));
        buttonsPanel.add(createButton(ADD_SHIP));
        return buttonsPanel;
    

    private JPanel createForm() 
        JPanel form = new JPanel(new GridBagLayout());
        form.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        GridBagConstraints gbc = new GridBagConstraints();

        // Initialize 'GridBagConstraints'.
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.insets.bottom = 2;
        gbc.insets.left = 2;
        gbc.insets.right = 2;
        gbc.insets.top = 2;

        // First row.
        addLabelToForm(form, "Ship Name:", gbc);
        nameText = getTextField();
        gbc.gridx = 1;
        form.add(nameText, gbc);
        gbc.gridx = 2;
        addColumnSpacer(form, gbc);
        gbc.gridx = 3;
        addLabelToForm(form, "Length at waterline:", gbc);
        lengthText = getTextField();
        gbc.gridx = 4;
        form.add(lengthText, gbc);

        // Second row.
        gbc.gridx = 0;
        gbc.gridy = 1;
        addLabelToForm(form, "Country of Registration:", gbc);
        flagText = getTextField();
        gbc.gridx = 1;
        form.add(flagText, gbc);
        gbc.gridx = 2;
        addColumnSpacer(form, gbc);
        gbc.gridx = 3;
        addLabelToForm(form, "Draft at waterline:", gbc);
        draftText = getTextField();
        gbc.gridx = 4;
        form.add(draftText, gbc);

        // Third row.
        gbc.gridx = 0;
        gbc.gridy = 2;
        addLabelToForm(form, "Year of Construction:", gbc);
        yearText = getTextField();
        gbc.gridx = 1;
        form.add(yearText, gbc);
        gbc.gridx = 2;
        addColumnSpacer(form, gbc);
        gbc.gridx = 3;
        addLabelToForm(form, "Beam at waterline:", gbc);
        beamText = getTextField();
        gbc.gridx = 4;
        form.add(beamText, gbc);
        return form;
    

    private JPanel createHeader() throws IOException 
        JPanel header = new JPanel();
        Icon ico = new ImageIcon(getClass().getResource("ship.png"));
        JLabel label = new JLabel("Select a ship", ico, SwingConstants.CENTER);
        header.add(label);
        DefaultComboBoxModel<ShipInfo> model = new DefaultComboBoxModel<>(getShips());
        shipsCombo = new JComboBox<>(model);
        shipsCombo.setSelectedIndex(-1); // No initial selection.
        shipsCombo.addItemListener(this);
        header.add(shipsCombo);
        return header;
    

    private String getIntText(int anInt) 
        return String.valueOf(anInt);
    

    private JTextField getTextField() 
        JTextField textField = new JTextField(15);
        textField.setHorizontalAlignment(JTextField.CENTER);
        return textField;
    

    private ShipInfo[] getShips() throws IOException 
        List<ShipInfo> lst = new ArrayList<>();
        try (FileReader fr = new FileReader("shipinfo.csv");
             BufferedReader br = new BufferedReader(fr)) 
            String line = br.readLine();
            while (line != null) 
                String[] flds = line.split(",");
                ShipInfo shipInfo = new ShipInfo(flds[0],
                                                 flds[1],
                                                 Integer.parseInt(flds[2]),
                                                 Integer.parseInt(flds[3]),
                                                 Integer.parseInt(flds[4]),
                                                 Integer.parseInt(flds[5]));
                lst.add(shipInfo);
                line = br.readLine();
            
        
    

    public static void main(String[] args) 
        String slaf = UIManager.getSystemLookAndFeelClassName();
        try 
            UIManager.setLookAndFeel(slaf);
        
        catch (ClassNotFoundException |
               IllegalAccessException |
               InstantiationException |
               UnsupportedLookAndFeelException x) 
            x.printStackTrace();
        
        final ShipsGui gui = new ShipsGui();
        EventQueue.invokeLater(() -> 
            try 
                gui.createAndDisplayGui();
            
            catch (IOException xIo) 
                throw new RuntimeException(xIo);
            
        );
    

shipsCombo 显示ShipInfo 对象的列表。该列表是从 CSV 文件中获取的。方法getShips 逐行读取文件。 ShipInfo 对象是根据文件单行中的数据创建的。创建一个包含所有ShipInfo 对象的数组,并且该数组用于为shipsCombo 创建模型。注意getShips方法使用try-with-resources。

[content pane 的]JFrame 的默认layout manager 是BorderLayout。顶部组件是shipsComboJLabelJLabel 包含文本和图标。中心组件是所有JTextFields,在shipsCombo中显示所选船的详细信息。在底部组件中是JButtons。

请注意,我从以下 *** 问题的答案中获得了将 JTextField 中的文本居中的代码:

How do I center a JTextfield

shipsCombo中的选中项改变时,方法itemStateChanged被调用。所选项目是类ShipInfo 的一个实例。从所选项目中提取详细信息并显示在相应的JTextFields 中。

当任何一个JButtons 被点击时,方法actionPerformed 被调用。我不想猜测 Add Ship 按钮应该做什么,所以上面的代码只是显示一条消息,说明按钮操作尚未实现。

这是在我的装有 JDK 17 的 Windows 10 计算机上运行的应用程序的屏幕截图。

【讨论】:

以上是关于如何将特定数据字段从 ArrayList 加载到某些 JTextFields?的主要内容,如果未能解决你的问题,请参考以下文章

从 ArrayList 访问特定对象字段

Hive如何根据表中某个字段动态分区

如何在webview加载完成后将滚动条定位到某一个指定位置

从文件中重复写入和加载对象的 ArrayList

将arrayList数据加载到JTable中

如何从Swift中的Cloud FireStore Firebase访问特定字段