Delete row from JTable

北慕城南 提交于 2021-01-28 14:50:44

问题


I need to remove row from JTable.

Here is my code :

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.GridLayout;


import javax.swing.JPanel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import java.util.ArrayList;
import javax.swing.table.DefaultTableModel;

public class GuiManyComponents implements ItemListener, ActionListener {
 public static void main(String[] args) {
  new GuiManyComponents();
}

JTextField txtField1;
JTextArea tarMultipleLines;
JButton btnDelete;
JButton btnAdd;
JButton btnEdit;
JButton ok;
JButton cancel;
JTable table = new JTable();
JTextField title;
JTextField description;
JTextField genre;
JTextField director;
JTextField rating;


ArrayList<Movie> movies = new ArrayList<Movie>();

public GuiManyComponents()
{

    final JFrame frame = new JFrame();
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.setLayout(new BorderLayout());
  frame.setSize(500,700);
  frame.setTitle("Text area test");


  final JFrame frame1 = new JFrame();
  frame1.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE );
  frame1.setLayout(new BorderLayout());
  frame1.setTitle("Text area test");

  final JFrame frame2 = new JFrame();
  frame2.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE );
  frame2.setLayout(new BorderLayout());
  frame2.setTitle("Text area test");

  table.getSelectedRow();


//test data
  movies.add(new Movie("1ABC", "D", "1", "qq", ""));
  movies.add(new Movie("2ABC", "F", "2", "", ""));
  movies.add(new Movie("3ABC", "G", "3", "", ""));

  updateJTable();

  JPanel south = new JPanel(new GridLayout(1, 3));
  south.add(btnDelete = new JButton("Delete", new ImageIcon("images\\nocheck.png")));
  btnDelete.addActionListener(this);

  south.add(btnEdit = new JButton("Change info", new ImageIcon("images\\paste.png")));
  btnEdit.addActionListener(
        new ActionListener(){
           public void actionPerformed(ActionEvent arg0)
           {
              frame.setVisible(false);
              frame2.setVisible(true);
           }
        });

  south.add(btnAdd = new JButton("Add New", new ImageIcon("images\\add.png")));
  btnAdd.addActionListener(
        new ActionListener(){
           public void actionPerformed(ActionEvent arg0)
           {
              frame.setVisible(false);
              frame1.setVisible(true);
           }
        });

  JScrollPane scrollPane = new JScrollPane(table); //add scrollpane to table


  frame.add(scrollPane, BorderLayout.CENTER);
  frame.add(south, BorderLayout.SOUTH);

  JPanel down = new JPanel(new GridLayout(1, 2));
  down.add(cancel = new JButton("Cancel", new ImageIcon("images\\nocheck.png")));
  cancel.addActionListener(
        new ActionListener(){
           public void actionPerformed(ActionEvent arg0)
           {
              frame.setVisible(true);
              frame1.setVisible(false);
           }
        });


     down.add(ok = new JButton("Save", new ImageIcon("images\\checkmark.png")));
     ok.setPreferredSize(new Dimension(100, 70));
     ok.addActionListener(new ActionListener(){
     public void actionPerformed(ActionEvent arg3)
     {

     String input = title.getText();
     String input2 = genre.getText();         
     String input3 = description.getText();         
     String input4 = director.getText();
     String input5 = rating.getText();         
     movies.add(new Movie(input, input2, input3, input4, input5 ));

     frame.setVisible(true);
     frame1.setVisible(false);

     updateJTable();
     }});

  title = new JTextField(5);
  description = new JTextField(5);
  director = new JTextField(5);
  rating = new JTextField(5);
  genre = new JTextField(5);

  title.addActionListener(this); // add actionListener
  description.addActionListener(this);
  rating.addActionListener(this);
  genre.addActionListener(this);
  director.addActionListener(this);

  JPanel north = new JPanel(new GridLayout(5, 2));
  north.add(new JLabel("Title: "));
  north.add(title);
  north.add(new JLabel("Director: "));
  north.add(director);
  north.add(new JLabel("Description: "));
  north.add(description);
  north.add(new JLabel("Genre: "));
  north.add(genre);
  north.add(new JLabel("Rating: "));
  north.add(rating);

  frame1.add(down, BorderLayout.SOUTH);
  frame1.add(north, BorderLayout.NORTH);
  frame1.pack();

  JPanel apacia = new JPanel(new GridLayout(1, 2));
  apacia.add(cancel = new JButton("Cancel", new ImageIcon("images\\nocheck.png")));
  cancel.addActionListener(
        new ActionListener(){
           public void actionPerformed(ActionEvent arg0)
           {
              frame.setVisible(true);
              frame2.setVisible(false);
           }
        });
  apacia.add(ok = new JButton("Done", new ImageIcon("images\\checkmark.png")));


  JPanel virsus = new JPanel(new GridLayout(5, 2));
  virsus.add(new JLabel("Title: "));
  virsus.add(title);
  virsus.add(new JLabel("Director: "));
  virsus.add(director);
  virsus.add(new JLabel("Description: "));
  virsus.add(description);
  virsus.add(new JLabel("Genre: "));
  virsus.add(rating);
  virsus.add(new JLabel("Rating: "));
  virsus.add(genre);

  frame2.add(virsus, BorderLayout.NORTH);
  frame2.add(apacia, BorderLayout.SOUTH);
  frame2.pack();

  frame.setVisible(true);
  frame1.setVisible(false);
  frame2.setVisible(false);
 }



   public void updateJTable()
 {
  DefaultTableModel model = new DefaultTableModel();

  model.setColumnIdentifiers(new String[] { "title", "genre", "description", "director", "rating" });
  model.setRowCount(movies.size());
  int row = 0;
  for (Movie movie : movies) {
     model.setValueAt(movie.getTitle(), row, 0);
     model.setValueAt(movie.getGenre(), row, 1);
     model.setValueAt(movie.getDescription(), row, 2);
     model.setValueAt(movie.getDirector(), row, 3);
     model.setValueAt(movie.getRating(), row, 4);
     row++;
  }
  table.setModel(model);
  }

  public void actionPerformed(ActionEvent arg0)
    {   
   }

 public void itemStateChanged( ItemEvent event )
   {
    }
   } 

I just now start to do GUI and it is a litle bit hard.

If you could help, I will be very thenksfull.


回答1:


Deleting a single row from the table is simple. You use code like:

int row = table.getSelectedRow();
DefaultTableModel model = (DefaultTableModel)table.getModel();
model.removeRow( row );

However the selected row in the table may not match the row in the TableModel because you may be sorting or filtering the table. So you need an extra step to convert the row in the table to the row in the model:

int row = table.getSelectedRow();
int modelRow = table.convertRowIndexToModel( row );
DefaultTableModel model = (DefaultTableModel)table.getModel();
model.removeRow( modelRow );

It can get even more confusing when you want to delete multiple rows at one time. As you remove one row all the data in the TableModel shifts by one row so your indexes are now off.

Following is example code that shows you how to remove multiple rows of data from a JList and a JTable:

import java.awt.*;
import java.awt.event.*;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.*;
import javax.swing.table.*;

public class ItemDeletion extends JPanel
{
    private JList<String> list;
    private JTable table;

    public ItemDeletion()
    {
        setLayout( new BorderLayout(5, 5) );

        String[] items =
        {
            "One",
            "Two",
            "Three",
            "Four",
            "Five",
            "Six",
            "Seven",
            "Eight",
            "Nine",
            "Ten"
        };

        //  Add the list

        DefaultListModel<String> listModel = new DefaultListModel<String>();

        for (String item: items)
            listModel.addElement( item );

        list = new JList<String>( listModel );


        JButton listDelete = new JButton( "Delete From List" );
        listDelete.addActionListener( new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                DefaultListModel model = (DefaultListModel)list.getModel();
                int row = list.getSelectedIndex();

                while (row != -1)
                {
                    model.removeElementAt( row );
                    row = list.getSelectedIndex();
                }
            }
        });

        JPanel listPanel = new JPanel( new BorderLayout(5, 5) );
        listPanel.add(new JScrollPane( list ), BorderLayout.CENTER);
        listPanel.add(listDelete, BorderLayout.PAGE_END);

        //  Add the table

        DefaultTableModel tableModel = new DefaultTableModel(0, 1);
        List<String> tableItems = Arrays.asList( items );
        Collections.shuffle( tableItems );

        for (String item: tableItems)
        {
            System.out.println( item );
            tableModel.addRow( new String[]{item} );
        }

        table = new JTable( tableModel );

        table.setAutoCreateRowSorter(true);
        ((DefaultRowSorter)table.getRowSorter()).toggleSortOrder(0);

        JButton tableDelete = new JButton( "Delete From Table" );
        tableDelete.addActionListener( new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                DefaultTableModel model = (DefaultTableModel)table.getModel();
                int row = table.getSelectedRow();

                while (row != -1)
                {
                    int modelRow = table.convertRowIndexToModel( row );
                    model.removeRow( modelRow );
                    row = table.getSelectedRow();
                }
            }
        });

        JPanel tablePanel = new JPanel( new BorderLayout(5, 5) );
        tablePanel.add(new JScrollPane( table ), BorderLayout.CENTER);
        tablePanel.add(tableDelete, BorderLayout.PAGE_END);

        add(listPanel, BorderLayout.LINE_START);
        add(tablePanel, BorderLayout.LINE_END);
    }

    private static void createAndShowGUI()
    {
        JFrame frame = new JFrame("Multiple Item Deletion");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new ItemDeletion(), BorderLayout.NORTH);
        frame.setLocationByPlatform( true );
        frame.pack();
        frame.setVisible( true );
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowGUI();
            }
        });
    }
}



回答2:


A JTable is usually part of an MVC architecture, i.e. it has a Model that it listens to for events (add/remove etc.). You should delete the desired data from the Model, have a look at DefaultTableModel




回答3:


I usually use this:

DefaultTableModel model = (DefaultTableModel) yourTable.getModel();
model.removeRow(indexOfRowToDelete);

Changing the model updates the content of your table inmediatly.




回答4:


The tricky thing with jTables is that they rely on a model (there are different classes for a table model, however for simple things like in your case I'd suggest you read the DefaultTableModel tutorial from java), basically each time you modify data from your table you have to create a new model and call the jTable.setModel(newModel), here is an example of how I did it:

  private void jAddActionPerformed(java.awt.event.ActionEvent evt) {                                           
    // TODO add your handling code here:
    Tm_prod tmp = new Tm_prod();
    TmTipoBD tmt = new TmTipoBD(con);

    //we add our new row logically
    list.add(element);

    //we create an empty DefaultTableModel
    DefaultTableModel model = new javax.swing.table.DefaultTableModel(
            new Object[][]{},
            new String[]{
                "Column1", "Column2", "Column3", "Column4"}
    ) {
        Class[] types = new Class[]{
            java.lang.Integer.class, java.lang.Integer.class, java.lang.Integer.class, java.lang.String.class
        };
        boolean[] canEdit = new boolean[]{
            false, false, false, false
        };

        @Override
        public Class getColumnClass(int columnIndex) {
            return types[columnIndex];
        }

        @Override
        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return canEdit[columnIndex];
        }
    };

    //we populate the recently created model with the new data
    for (Item i: list) {
        model.addRow(new Object[]{i.getProperty1(), i.getProperty2(), i.getProperty3(), i.getProperty()});
    }
    jTable.setModel(model);
  }


来源:https://stackoverflow.com/questions/29702044/delete-row-from-jtable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!