从ArrayList中删除特定字符串

时间:2016-03-13 00:47:38

标签: java swing arraylist

美好的一天,我试图完成删除ArrayList中特定字符串的任务,我认为它已被转换为默认列表? 但是,我遇到了一些困难,我想知道我做错了什么。 这是在JavaSwing中完成的,我将提供我认为删除它的方法,我相信我的问题是我不会更新列表。

我将提供我的主要jFrame:如果你想要任何其他课程,请告诉我,他们相当长。

package is.hi.torg.vidmot;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package is.hi.torg.vidmot;

import is.hi.torg.gogn.LagaListi;
import is.hi.torg.styring.StyringListi;
import is.hi.torg.vinnsla.FlokkarModel;
import is.hi.torg.vinnsla.LagaListiModel;
import is.hi.torg.vinnsla.TonlistarKatalogur;
import java.util.ArrayList;
import javax.swing.DefaultListModel;

/**
 *
 * @author Ebba Þóra Hvannberg ebba@hi.is
 */
public class AdalTorg extends javax.swing.JFrame {
    private final TonlistarKatalogur minnKatalogur;
    public AdgerdTag getAdgerd() {
        return adgerd;
    }

    /**
     * @param adgerd the adgerd to set
     */
    public void setAdgerd(AdgerdTag adgerd) {
        this.adgerd = adgerd;
    }

    public enum AdgerdTag {SKODA, EYDA, BREYTA};

    private AdgerdTag adgerd=AdgerdTag.SKODA;




    LagaListi minnLagaListi;
    /**
     * Creates new form AdalTorg
     */
    public AdalTorg() {
             initComponents();

        // Lesum inn XML gögn með því að smíða TónlistarKatalog
              minnKatalogur = new TonlistarKatalogur();


        // Birtum  lögin 

             minnKatalogur.birtaLogin();

              birtaLag(3);
        List.getSelectionModel().addListSelectionListener(new StyringListi(this));
              FlokkarModel fModel = new FlokkarModel(minnKatalogur.getFlokkar());
              jFlokkar.setModel(fModel.getModel());


              LagaListiModel list = new LagaListiModel(minnKatalogur.getLagaListi());
              List.setModel(list); 



    }

    public TonlistarKatalogur getTonlistarKatalog(){

        return minnKatalogur; 
    }
    private void printO(int i){
        jTextArea1.append("Flytjandi: " + minnKatalogur.getLagaListi().get(i).getFlytjandi() + "\n" + 
                      "Lag: " + minnKatalogur.getLagaListi().get(i).getTitill() + "\n" + 
                      "Höfundur: " + minnKatalogur.getLagaListi().get(i).getHofundur() + "\n" + 
                      "Flokkur :" + minnKatalogur.getLagaListi().get(i).getFlokkur().getHeiti() + "\n" +
                      "Undirflokkur: " + minnKatalogur.getLagaListi().get(i).getUndirflokkur().getHeiti() + "\n\n");
    }

    private void birtaLag(int indexLag) {


        System.out.println ("lag nr. "+(indexLag+1));
        System.out.println (
                minnKatalogur.getLagaListi().get(indexLag).getTitill());

         System.out.println (
        minnKatalogur.getLagaListi().get(indexLag).getFlytjandi());

        System.out.println (
        minnKatalogur.getLagaListi().get(indexLag).getFlokkur().getHeiti());

        System.out.println (
        minnKatalogur.getLagaListi().get(indexLag).getUndirflokkur().getHeiti());

           jTextArea1.setText("XML skrá komin!"); 
    }   

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jFlokkar = new javax.swing.JTree();
        jScrollPane2 = new javax.swing.JScrollPane();
        List = new javax.swing.JList<>();
        jButton1 = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        Delete_Me = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jScrollPane1.setViewportView(jFlokkar);

        List.setModel(new javax.swing.AbstractListModel<String>() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public String getElementAt(int i) { return strings[i]; }
        });
        List.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                ListMouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(List);

        jButton1.setText("Ok ");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane3.setViewportView(jTextArea1);

        Delete_Me.setText("Delete me");
        Delete_Me.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                Delete_MeActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(Delete_Me)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButton1))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 186, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(40, 40, 40)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 267, Short.MAX_VALUE)
                .addContainerGap())
            .addComponent(jScrollPane3)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jScrollPane2)
                    .addComponent(jScrollPane1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 56, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(Delete_Me)))
        );

        pack();
    }// </editor-fold>                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
jTextArea1.setText(""); 
jButton1.setVisible(false); 
    }                                        

    private void ListMouseClicked(java.awt.event.MouseEvent evt) {                                  
        dialog dlg = new dialog(this,true); 



                 //NamskeidDialog namskeidDialog = new NamskeidDialog (this, true);

    }                                 

    private void Delete_MeActionPerformed(java.awt.event.ActionEvent evt) {                                          
        setAdgerd(AdgerdTag.EYDA);


    }                                         

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */

        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(AdalTorg.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(AdalTorg.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(AdalTorg.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(AdalTorg.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }

        //</editor-fold>
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new AdalTorg().setVisible(true);
            }
        });
    }``

// AdalTorg是主要的JFrame,我唯一想知道的是我做错了什么,我非常肯定我没有在我删除之后更新列表它,如果是这样,我的错误在哪里,我在哪里修复它?

package is.hi.torg.styring;

import is.hi.torg.gogn.LagaListi;
import is.hi.torg.vidmot.AdalTorg;
import is.hi.torg.vidmot.dialog;
import is.hi.torg.vidmot.AdalTorg.AdgerdTag;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.event.ListSelectionListener;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;




/**
    *
 * @author Lenovo
 */
public class StyringListi implements ListSelectionListener{

private AdalTorg TorgAdal;
public StyringListi(AdalTorg Torg){

TorgAdal = Torg; 


}
@Override
 public void valueChanged (ListSelectionEvent evt) {
       ListSelectionModel lsm = (ListSelectionModel)evt.getSource();


       AdgerdTag a = TorgAdal.getAdgerd();
       int index = lsm.getMinSelectionIndex();  
       switch(a){
           case SKODA: 
               Printo(index); 
               break;


                 case BREYTA:

               break; 
           case EYDA:
               EydO(index); 





       }
            TorgAdal.setAdgerd(AdgerdTag.SKODA);
 }




 private void Printo(int i){

     dialog Dialog = new dialog(TorgAdal,true); 
      Dialog.TextO.append("Flytjandi:"+ TorgAdal.getTonlistarKatalog().getLagaListi().get(i).getFlytjandi()+"\n"+
                          "Lag: " + TorgAdal.getTonlistarKatalog().getLagaListi().get(i).getTitill() + "\n" + 
                          "Höfundur: " + TorgAdal.getTonlistarKatalog().getLagaListi().get(i).getHofundur() + "\n" +
                          "Flokkur :" + TorgAdal.getTonlistarKatalog().getLagaListi().get(i).getFlokkur().getHeiti() + "\n" +
                          "Undirflokkur: " + TorgAdal.getTonlistarKatalog().getLagaListi().get(i).getUndirflokkur().getHeiti() + "\n\n");

     Dialog.setVisible(true); 
      //"Flytjandi: " + minnKatalogur.getLagaListi().get(i).getFlytjandi() + "\n" + 
            //          "Lag: " + minnKatalogur.getLagaListi().get(i).getTitill() + "\n" + 
             //         "Höfundur: " + minnKatalogur.getLagaListi().get(i).getHofundur() + "\n" + 
              //        "Flokkur :" + minnKatalogur.getLagaListi().get(i).getFlokkur().getHeiti() + "\n" +
                //      "Undirflokkur: " + minnKatalogur.getLagaListi().get(i).getUndirflokkur().getHeiti() + "\n\n");


 }
  private void EydO(int i){

          if (i == -1)
              return;
          String s = TorgAdal.getTonlistarKatalog().getLagaListi().get(i).getTitill();
           if (JOptionPane.showConfirmDialog(TorgAdal, "Viltu eyða námskeiðinu? "+s, "Laginu", JOptionPane.YES_NO_OPTION)==0)

                TorgAdal.getTonlistarKatalog().eydaLagi(i);



 }


}

//我认为这是控制List的功能。

编辑,此函数假设为DefaultArrayList。

package is.hi.torg.vinnsla;

import is.hi.torg.gogn.LagaListi;
import java.util.ArrayList;
import javax.swing.DefaultListModel;

/**
 *
 * @author Lenovo
 */
public class LagaListiModel extends DefaultListModel {

    public LagaListiModel( ArrayList<LagaListi.Lag> lagaListi){



        for(int i = 0; i <lagaListi.size();i++)
        {
        String s = lagaListi.get(i).getTitill();
        this.addElement(s);

        }

    }




}
And here I call on all the functions, am I doing it incorrectly?


public AdalTorg() {
                 initComponents();

            // Lesum inn XML gögn með því að smíða TónlistarKatalog
                  minnKatalogur = new TonlistarKatalogur();


            // Let's show some songs

                 minnKatalogur.birtaLogin();

                  birtaLag(3);
            List.getSelectionModel().addListSelectionListener(new StyringListi(this));
                  FlokkarModel fModel = new FlokkarModel(minnKatalogur.getFlokkar());
                  jFlokkar.setModel(fModel.getModel());


                  LagaListiModel list = new LagaListiModel(minnKatalogur.getLagaListi());
                  List.setModel(list); 



        }




   public TonlistarKatalogur getTonlistarKatalog(){

        return minnKatalogur; 
    }
    private void printO(int i){
        jTextArea1.append("Flytjandi: " + minnKatalogur.getLagaListi().get(i).getFlytjandi() + "\n" + 
                      "Lag: " + minnKatalogur.getLagaListi().get(i).getTitill() + "\n" + 
                      "Höfundur: " + minnKatalogur.getLagaListi().get(i).getHofundur() + "\n" + 
                      "Flokkur :" + minnKatalogur.getLagaListi().get(i).getFlokkur().getHeiti() + "\n" +
                      "Undirflokkur: " + minnKatalogur.getLagaListi().get(i).getUndirflokkur().getHeiti() + "\n\n");
    }

1 个答案:

答案 0 :(得分:2)

  1. 变量名称不应以大写字母开头。

  2. 方法名称不应以大写字母开头。

  3. 班级名称应该以大写字母开头。

  4. 类名应该是描述性的。 “对话框”不具有描述性,并且不以大写字母开头。

  5.   

    我正在尝试删除ArrayList中的特定字符串,我认为它已被转换为默认列表?

    我甚至没有看到你在代码中使用ArrayList的位置。

      

    我认为这是引导名单的功能。

    好吧,如果你不知道你怎么想我们知道?

      

    List.setModel(new javax.swing.AbstractListModel()

    您正在使用不支持remove()方法的AbstractListModel。使用DefaultListModel。

    首先阅读How to Use Lists上的Swing教程中的部分。 ListDemo示例显示了如何从列表中动态添加和删除项目。

    下载演示代码并使用它,然后修改代码。