简体   繁体   English

从ArrayList和Jlist中的相应索引中删除对象

[英]Deleting an object from an ArrayList and the corresponding index in a Jlist

I have a class that reads a object file and imports it in an ArrayList. 我有一个读取对象文件并将其导入ArrayList的类。 Then I made a Jlist to show some of the information of each objectfrom that ArrayList. 然后,我创建了一个Jlist,以显示该ArrayList中每个对象的一些信息。 So when they select an element of the Jlist, it will show the entire corresponding index object from the ArrayList. 因此,当他们选择Jlist的元素时,它将显示ArrayList中的整个对应索引对象。 I want to add a "Delete" button to remove the selected Jlist element and the corresponding index object from the ArrayList. 我想添加一个“删除”按钮以从ArrayList中删除所选的Jlist元素和相应的索引对象。 And then update the Jlist showing that element is deleted. 然后更新显示该元素已删除的Jlist。

This is my class: 这是我的课:

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Font;
import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.util.ArrayList;

import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.ListModel;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.JScrollPane;
import javax.swing.JList;

import java.awt.TextArea;

import javax.swing.JTable;
import javax.swing.JTextPane;
import javax.swing.JTextArea;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JTextField;
import javax.swing.JButton;

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


public class LogBook2 extends JFrame {


    private static ArrayList<Log> logList = new ArrayList<Log>();



    private static String logs;



    private JPanel contentPane;
    private JScrollPane scrollPane;
    private JList list;
    private JScrollPane scrollPane_1;
    private String tpContent;

    private int diveNumber;
    private int diveDate;
    private String diveMonth;
    private int diveYear;
    private String location;
    private String diveSite;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    LogBook frame = new LogBook();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public LogBook2() {


        //===============================================================================
        //Importing form the Object file to ArrayList "logList" 
        File fileOfLogs=new File("logList.txt");
        if(fileOfLogs.exists()){
            try{
                ObjectInputStream myStream = new ObjectInputStream(new FileInputStream("logList.txt"));

                logList = (ArrayList<Log>) myStream.readObject();



                myStream.close();


            }
            catch(Exception e){
                setVisible(false);
                JOptionPane.showMessageDialog(null, " 00000 There was a problem while reading dive records.\n "
                        + "Please contact SEASFiRE Tech Team.", "Error", JOptionPane.ERROR_MESSAGE);

            }

        }
        else if(!fileOfLogs.exists()){
            JOptionPane.showMessageDialog(null, " 11111 There was a problem while reading dive records.\n "
                    + "Please contact SEASFiRE Tech Team.", "Error", JOptionPane.ERROR_MESSAGE);

        }
        //===============================================================================

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 888, 680);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);



        JScrollPane scrollPane_2 = new JScrollPane();
        scrollPane_2.setBounds(10, 88, 297, 542);
        contentPane.add(scrollPane_2);

        JList list_1 = new JList();
        scrollPane_2.setViewportView(list_1);
        list_1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);


        //===============================================================================
        //getting some information of each object and making a Jlist element with it.
        DefaultListModel model=new DefaultListModel();
        for( int i=0;i<logList.size();i++){



            model.addElement(""+logList.get(i).getDiveNumber()+"__"+logList.get(i).getDiveDate()+"/"+logList.get(i).getDiveMonth()+"/"+logList.get(i).getDiveYear()
                    +"__"+logList.get(i).getLocation()+"_"+logList.get(i).getDiveSite());

        }

        list_1.setModel(model);


        //===============================================================================



        JLabel lblAddNewLog = new JLabel("Log Book");
        lblAddNewLog.setHorizontalAlignment(SwingConstants.CENTER);
        lblAddNewLog.setFont(new Font("Myanmar Text", Font.BOLD, 40));
        lblAddNewLog.setBounds(0, 16, 862, 61);
        contentPane.add(lblAddNewLog);



        scrollPane = new JScrollPane();
        scrollPane.setBounds(317, 88, 322, 542);
        contentPane.add(scrollPane);

        JTextArea textArea = new JTextArea();
        textArea.setEditable(false);
        scrollPane.setViewportView(textArea);
        JButton btnDelete = new JButton("Delete");
        //===============================================================================
        //trying to make the "Delete" button. Not working...
        btnDelete.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {


                model.remove(list_1.getSelectedIndex());
                list_1.remove(list_1.getSelectedIndex());
                textArea.setText("");
                list_1.clearSelection();






            }
        });
        btnDelete.setBounds(649, 561, 115, 29);
        contentPane.add(btnDelete);
        //========================================================================




        //========================================================================
        //the action for when an element is selected.
        list_1.addListSelectionListener(
                new ListSelectionListener(){
                    public void valueChanged(ListSelectionEvent event){
                        textArea.setText("");
                        textArea.append("Dive Number: "+logList.get(list_1.getSelectedIndex()).getDiveNumber()+"\t\tDive Date: "+
                    logList.get(list_1.getSelectedIndex()).getDiveDate()+"/"+logList.get(list_1.getSelectedIndex()).getDiveMonth()+
                    "/"+logList.get(list_1.getSelectedIndex()).getDiveYear()+"\n\nLocation: "+logList.get(list_1.getSelectedIndex()).getLocation()+
                    "\n\nDive Site: "+logList.get(list_1.getSelectedIndex()).getDiveSite()+"\n\nDive Type: "+logList.get(list_1.getSelectedIndex()).getDiveType()+
                    "\t\tCondition: "+logList.get(list_1.getSelectedIndex()).getCondition()+"\n\nVisibility: "+logList.get(list_1.getSelectedIndex()).getVisibility()+
                    "m\t\tSuit Type: "+logList.get(list_1.getSelectedIndex()).getSuitType()+"\n\nWeights: "+logList.get(list_1.getSelectedIndex()).getWeight()+
                    "m\t\tAltitude: "+logList.get(list_1.getSelectedIndex()).getAltitude()+"m\n\nTime In: "+logList.get(list_1.getSelectedIndex()).getHourIn()+
                    ":"+logList.get(list_1.getSelectedIndex()).getMinIn()+"\t\tDuration: "+logList.get(list_1.getSelectedIndex()).getDuration()+
                    "min\n\nMax Depth: "+logList.get(list_1.getSelectedIndex()).getMaxDepth()+"m\t\tSafety Stop: "+logList.get(list_1.getSelectedIndex()).getSafetyStop()+
                    "\n\nAir in: "+logList.get(list_1.getSelectedIndex()).getAirIn()+"bar\t\tAir Out: "+logList.get(list_1.getSelectedIndex()).getAirOut()+
                    "bar\n\n02 Perc: "+logList.get(list_1.getSelectedIndex()).getOxgPerc()+"%\t\tDive Buddy: "+logList.get(list_1.getSelectedIndex()).getDiveBuddy()+
                    "\n\nNote: "+logList.get(list_1.getSelectedIndex()).getNote());


                    }
                }
            );



        //========================================================================







    }
}

Don't keep a separate ArrayList to hold the data. 不要保留单独的ArrayList来保存数据。

Instead all the data should be stored in the ListModel 相反,所有数据都应存储在ListModel中

DefaultListModel<Log> model = new DefaultListModel<Log>();
model.addElement(...);
JList<Log> list = new JList<Log>( model );

Then you create a custom renderer for the JList to display whatever data from the Log class that you want: 然后,为JList创建一个自定义渲染器,以显示所需的Log类中的任何数据:

list.setCellRenderer( new DefaultListCellRenderer()
{
    public Component getListCellRendererComponent(
            JList list, Object value, int index, boolean isSelected, boolean cellHasFocus)
    {
        super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
        Log log = (Log)value;
        setText( log.get...() ):
        return this;
    }
});

Now you only have data in one place so when you want to delete a row you just delete the row from the DefaultListModel. 现在,您仅将数据放在一个位置,因此,要删除行时,只需从DefaultListModel中删除该行。

If you want to know how to delete an entry from the ListModel then take a look at the section from the Swing tutorial on How to Use Lists . 如果您想知道如何从ListModel中删除条目,请查看Swing教程中有关如何使用列表的部分 The "Fire" button will delete the selected row. “火灾”按钮将删除所选的行。 The tutorial will also explain more about using a custom renderer. 本教程还将说明有关使用自定义渲染器的更多信息。

add a toString() method to your Log class. 将toString()方法添加到Log类。

public void toString(){
    return "" + getDiveNumber()+"__"+getDiveDate()+"/"+getDiveMonth()+"/"+getDiveYear() +"__"+getLocation()+"_"+getDiveSite();
}

then add listmodel log instances 然后添加listmodel日志实例

model.addElement(logList.get(i));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM