Java Tutorial/Swing/Table Selection

Материал из Java эксперт
Перейти к: навигация, поиск

Allow multiple selections of rows, visible columns, or cell blocks (default)

import javax.swing.JTable;
import javax.swing.ListSelectionModel;
public class Main {
  public static void main(String[] argv) throws Exception {
    JTable table = new JTable();
    table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
  }
}





Allow only single a selection

import javax.swing.JTable;
import javax.swing.ListSelectionModel;
public class Main {
  public static void main(String[] argv) throws Exception {
    JTable table = new JTable();
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
  }
}





Allow selection to span one contiguous set of rows, visible columns, or block of cells

import javax.swing.JTable;
import javax.swing.ListSelectionModel;
public class Main {
  public static void main(String[] argv) throws Exception {
    JTable table = new JTable();
    table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
  }
}





Check each cell in the min and max ranges of selected cells

import javax.swing.JTable;
import javax.swing.ListSelectionModel;
public class Main {
  public static void main(String[] argv) throws Exception {
    JTable table = new JTable();
    if (table.getCellSelectionEnabled()) {
      // In the other modes, the set of selected cells can be retrieved using
      table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
      table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
      // Get the min and max ranges of selected cells
      int rowIndexStart = table.getSelectedRow();
      int rowIndexEnd = table.getSelectionModel().getMaxSelectionIndex();
      int colIndexStart = table.getSelectedColumn();
      int colIndexEnd = table.getColumnModel().getSelectionModel().getMaxSelectionIndex();
      // Check each cell in the range
      for (int r = rowIndexStart; r <= rowIndexEnd; r++) {
        for (int c = colIndexStart; c <= colIndexEnd; c++) {
          if (table.isCellSelected(r, c)) {
            System.out.println("cell is selected"); 
          }
        }
      }
    }
  }
}





Deselect a cell: cell (3,2), All cells in the row and column containing (re deselected.

import javax.swing.JTable;
import javax.swing.ListSelectionModel;
public class Main {
  public static void main(String[] argv) throws Exception {
    int rows = 10;
    int cols = 5;
    JTable table = new JTable(rows, cols);
    table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    table.setColumnSelectionAllowed(true);
    table.setRowSelectionAllowed(true);
    int row = 3;
    int col = 2;
    boolean toggle = true;
    boolean extend = false;
    table.changeSelection(row, col, toggle, extend);
  }
}





Disabling Selections in a JTable Component

import javax.swing.JTable;
public class Main {
  public static void main(String[] argv) throws Exception {
    int rows = 10;
    int cols = 5;
    JTable table = new JTable(rows, cols);
    table.setFocusable(false);
    table.setCellSelectionEnabled(false);
  }
}





Extend the selection to include all cells (5,3)

import javax.swing.JTable;
import javax.swing.ListSelectionModel;
public class Main {
  public static void main(String[] argv) throws Exception {
    int rows = 10;
    int cols = 5;
    JTable table = new JTable(rows, cols);
    table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    table.setColumnSelectionAllowed(true);
    table.setRowSelectionAllowed(true);
    int row = 5;
    int col = 3;
    boolean toggle = false;
    boolean extend = true;
    table.changeSelection(row, col, toggle, extend);
  }
}





Get default selection mode:MULTIPLE_INTERVAL_SELECTION

import javax.swing.JTable;
public class Main {
  public static void main(String[] argv) throws Exception {
    JTable table = new JTable();
    int selMode = table.getSelectionModel().getSelectionMode();
  }
}





Get selected row and selected index

import javax.swing.JTable;
import javax.swing.ListSelectionModel;
public class Main {
  public static void main(String[] argv) throws Exception {
    JTable table = new JTable();
    if (table.getCellSelectionEnabled()) {
      table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
      int rowIndex = table.getSelectedRow();
      int colIndex = table.getSelectedColumn();
    }
  }
}





Get the min and max ranges of selected cells

import javax.swing.JTable;
import javax.swing.ListSelectionModel;
public class Main {
  public static void main(String[] argv) throws Exception {
    JTable table = new JTable();
    if (table.getCellSelectionEnabled()) {
      table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
      table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
      int rowIndexStart = table.getSelectedRow();
      int rowIndexEnd = table.getSelectionModel().getMaxSelectionIndex();
      int colIndexStart = table.getSelectedColumn();
      int colIndexEnd = table.getColumnModel().getSelectionModel().getMaxSelectionIndex();
    }
  }
}





Getting the Anchor Cell in a JTable Component

import javax.swing.JTable;
public class Main {
  public static void main(String[] argv) throws Exception {
    int rows = 10;
    int cols = 5;
    JTable table = new JTable(rows, cols);
    int rowIndex = table.getSelectionModel().getAnchorSelectionIndex();
    int vColIndex = table.getColumnModel().getSelectionModel().getAnchorSelectionIndex();
  }
}





Handle selection and model change events for a JTable.

import java.awt.Dimension;
import java.util.Date;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableModel;
public class Main implements ListSelectionListener {
  String[] headings = { "Name", "Customer ID", "Order #", "Status" };
  Object[][] data = { { "A", new Integer(3), "0", new Date() },
      { "B", new Integer(6), "4", new Date() }, { "C", new Integer(9), "9", new Date() },
      { "D", new Integer(7), "1", new Date() }, { "E", new Integer(4), "1", new Date() },
      { "F", new Integer(8), "2", new Date() }, { "G", new Integer(6), "1", new Date() } };
  JTable jtabOrders = new JTable(data, headings);
  TableModel tm;
  Main() {
    JFrame jfrm = new JFrame("JTable Event Demo");
    jfrm.setSize(400, 200);
    jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    jtabOrders.setPreferredScrollableViewportSize(new Dimension(420, 62));
    ListSelectionModel rowSelMod = jtabOrders.getSelectionModel();
    ListSelectionModel colSelMod = jtabOrders.getColumnModel().getSelectionModel();
    rowSelMod.addListSelectionListener(this);
    colSelMod.addListSelectionListener(this);
    tm = jtabOrders.getModel();
    tm.addTableModelListener(new TableModelListener() {
      public void tableChanged(TableModelEvent tme) {
        if (tme.getType() == TableModelEvent.UPDATE) {
          System.out.println("Cell " + tme.getFirstRow() + ", " + tme.getColumn() + " changed."
              + " The new value: " + tm.getValueAt(tme.getFirstRow(), tme.getColumn()));
        }
      }
    });
    jfrm.add(new JScrollPane(jtabOrders));
    jfrm.setVisible(true);
  }
  public void valueChanged(ListSelectionEvent le) {
    String str = "Selected Row(s): ";
    int[] rows = jtabOrders.getSelectedRows();
    for (int i = 0; i < rows.length; i++)
      str += rows[i] + " ";
    str += "Selected Column(s): ";
    int[] cols = jtabOrders.getSelectedColumns();
    for (int i = 0; i < cols.length; i++)
      str += cols[i] + " ";
    str += "Selected Cell: " + jtabOrders.getSelectedRow() + ", "
        + jtabOrders.getSelectedColumn();
    System.out.println(str);
  }
  public static void main(String args[]) {
    new Main();
  }
}





JTable.setCellSelectionEnabled(boolean b);

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.util.Date;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
public class Main {
  String[] headings = { "Name", "Customer ID","Order #", "Status" };
  Object[][] data = {
    { "A", new Integer(3), "0", new Date() },
    { "B", new Integer(6), "4", new Date() },
    { "C", new Integer(9), "9", new Date() },
    { "D", new Integer(7), "1", new Date() },
    { "E", new Integer(4), "1", new Date() },
    { "F", new Integer(8), "2", new Date() },
    { "G", new Integer(6), "1", new Date() }
  };
  JTable jtabOrders = new JTable(data, headings);
  Main() {
    JFrame jfrm = new JFrame("JTable Demo");
    jfrm.setLayout(new FlowLayout());
    jfrm.setSize(460, 180);
    jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JScrollPane jscrlp = new JScrollPane(jtabOrders);
    jtabOrders.setPreferredScrollableViewportSize(new Dimension(420, 60));
    jtabOrders.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    jtabOrders.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    jfrm.setVisible(true);
  
    jtabOrders.setCellSelectionEnabled(true);
  }
  public static void main(String args[]) {
     new Main();
  }
}





JTable.setColumnSelectionAllowed(boolean b);

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.util.Date;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
public class Main {
  String[] headings = { "Name", "Customer ID",
                        "Order #", "Status" };
  Object[][] data = {
    { "A", new Integer(3), "0", new Date() },
    { "B", new Integer(6), "4", new Date() },
    { "C", new Integer(9), "9", new Date() },
    { "D", new Integer(7), "1", new Date() },
    { "E", new Integer(4), "1", new Date() },
    { "F", new Integer(8), "2", new Date() },
    { "G", new Integer(6), "1", new Date() }
  };
  JTable jtabOrders = new JTable(data, headings);
  Main() {
    JFrame jfrm = new JFrame("JTable Demo");
    jfrm.setLayout(new FlowLayout());
    jfrm.setSize(460, 180);
    jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JScrollPane jscrlp = new JScrollPane(jtabOrders);
    jtabOrders.setPreferredScrollableViewportSize(
                new Dimension(420, 60));
    jtabOrders.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    jfrm.setVisible(true);
  
    jtabOrders.setColumnSelectionAllowed(false);
    jtabOrders.setRowSelectionAllowed(true);
  }
  public static void main(String args[]) {
     new Main();
  }
}





JTable.setRowSelectionAllowed(boolean b);

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.util.Date;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
public class Main {
  String[] headings = { "Name", "Customer ID","Order #", "Status" };
  Object[][] data = {
    { "A", new Integer(3), "0", new Date() },
    { "B", new Integer(6), "4", new Date() },
    { "C", new Integer(9), "9", new Date() },
    { "D", new Integer(7), "1", new Date() },
    { "E", new Integer(4), "1", new Date() },
    { "F", new Integer(8), "2", new Date() },
    { "G", new Integer(6), "1", new Date() }
  };
  JTable jtabOrders = new JTable(data, headings);
  Main() {
    JFrame jfrm = new JFrame("JTable Demo");
    jfrm.setLayout(new FlowLayout());
    jfrm.setSize(460, 180);
    jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JScrollPane jscrlp = new JScrollPane(jtabOrders);
    jtabOrders.setPreferredScrollableViewportSize(
                new Dimension(420, 60));
    jtabOrders.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    jfrm.setVisible(true);
  
    jtabOrders.setColumnSelectionAllowed(false);
    jtabOrders.setRowSelectionAllowed(true);
  }
  public static void main(String args[]) {
     new Main();
  }
}





JTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.util.Date;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
public class Main {
  String[] headings = { "Name", "Customer ID", "Order #", "Status" };
  Object[][] data = {
    { "A", new Integer(3), "0", new Date() },
    { "B", new Integer(6), "4", new Date() },
    { "C", new Integer(9), "9", new Date() },
    { "D", new Integer(7), "1", new Date() },
    { "E", new Integer(4), "1", new Date() },
    { "F", new Integer(8), "2", new Date() },
    { "G", new Integer(6), "1", new Date() }
  };
  JTable jtabOrders = new JTable(data, headings);
  Main() {
    JFrame jfrm = new JFrame("JTable Demo");
    jfrm.setLayout(new FlowLayout());
    jfrm.setSize(460, 180);
    jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JScrollPane jscrlp = new JScrollPane(jtabOrders);
    jtabOrders.setPreferredScrollableViewportSize(new Dimension(420, 60));
    jtabOrders.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    jfrm.setVisible(true);
  
    jtabOrders.setColumnSelectionAllowed(false);
    jtabOrders.setRowSelectionAllowed(true);
  }
  public static void main(String args[]) {
     new Main();
  }
}





JTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.util.Date;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
public class Main {
  String[] headings = { "Name", "Customer ID","Order #", "Status" };
  Object[][] data = {
    { "A", new Integer(3), "0", new Date() },
    { "B", new Integer(6), "4", new Date() },
    { "C", new Integer(9), "9", new Date() },
    { "D", new Integer(7), "1", new Date() },
    { "E", new Integer(4), "1", new Date() },
    { "F", new Integer(8), "2", new Date() },
    { "G", new Integer(6), "1", new Date() }
  };
  JTable jtabOrders = new JTable(data, headings);
  Main() {
    JFrame jfrm = new JFrame("JTable Demo");
    jfrm.setLayout(new FlowLayout());
    jfrm.setSize(460, 180);
    jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JScrollPane jscrlp = new JScrollPane(jtabOrders);
    jtabOrders.setPreferredScrollableViewportSize(new Dimension(420, 60));
    jtabOrders.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    jfrm.setVisible(true);
  
    jtabOrders.setColumnSelectionAllowed(false);
    jtabOrders.setRowSelectionAllowed(true);
  }
  public static void main(String args[]) {
     new Main();
  }
}





ListSelectionModel colSelMod = JTable.getColumnModel().getSelectionModel();

import java.awt.Dimension;
import java.util.Date;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableModel;
public class Main implements ListSelectionListener {
  String[] headings = { "Name", "Customer ID", "Order #", "Status" };
  Object[][] data = { { "A", new Integer(3), "0", new Date() },
      { "B", new Integer(6), "4", new Date() }, { "C", new Integer(9), "9", new Date() },
      { "D", new Integer(7), "1", new Date() }, { "E", new Integer(4), "1", new Date() },
      { "F", new Integer(8), "2", new Date() }, { "G", new Integer(6), "1", new Date() } };
  JTable jtabOrders = new JTable(data, headings);
  TableModel tm;
  Main() {
    JFrame jfrm = new JFrame("JTable Event Demo");
    jfrm.setSize(400, 200);
    jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    jtabOrders.setPreferredScrollableViewportSize(new Dimension(420, 62));
    ListSelectionModel rowSelMod = jtabOrders.getSelectionModel();
    ListSelectionModel colSelMod = jtabOrders.getColumnModel().getSelectionModel();
    rowSelMod.addListSelectionListener(this);
    colSelMod.addListSelectionListener(this);
    tm = jtabOrders.getModel();
    tm.addTableModelListener(new TableModelListener() {
      public void tableChanged(TableModelEvent tme) {
        if (tme.getType() == TableModelEvent.UPDATE) {
          System.out.println("Cell " + tme.getFirstRow() + ", " + tme.getColumn() + " changed."
              + " The new value: " + tm.getValueAt(tme.getFirstRow(), tme.getColumn()));
        }
      }
    });
    jfrm.add(new JScrollPane(jtabOrders));
    jfrm.setVisible(true);
  }
  public void valueChanged(ListSelectionEvent le) {
    String str = "Selected Row(s): ";
    int[] rows = jtabOrders.getSelectedRows();
    for (int i = 0; i < rows.length; i++)
      str += rows[i] + " ";
    str += "Selected Column(s): ";
    int[] cols = jtabOrders.getSelectedColumns();
    for (int i = 0; i < cols.length; i++)
      str += cols[i] + " ";
    str += "Selected Cell: " + jtabOrders.getSelectedRow() + ", "
        + jtabOrders.getSelectedColumn();
    System.out.println(str);
  }
  public static void main(String args[]) {
    new Main();
  }
}





ListSelectionModel rowSelMod = JTable.getSelectionModel();

import java.awt.Dimension;
import java.util.Date;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableModel;
public class Main implements ListSelectionListener {
  String[] headings = { "Name", "Customer ID", "Order #", "Status" };
  Object[][] data = { { "A", new Integer(3), "0", new Date() },
      { "B", new Integer(6), "4", new Date() }, { "C", new Integer(9), "9", new Date() },
      { "D", new Integer(7), "1", new Date() }, { "E", new Integer(4), "1", new Date() },
      { "F", new Integer(8), "2", new Date() }, { "G", new Integer(6), "1", new Date() } };
  JTable jtabOrders = new JTable(data, headings);
  TableModel tm;
  Main() {
    JFrame jfrm = new JFrame("JTable Event Demo");
    jfrm.setSize(400, 200);
    jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    jtabOrders.setPreferredScrollableViewportSize(new Dimension(420, 62));
    ListSelectionModel rowSelMod = jtabOrders.getSelectionModel();
    ListSelectionModel colSelMod = jtabOrders.getColumnModel().getSelectionModel();
    rowSelMod.addListSelectionListener(this);
    colSelMod.addListSelectionListener(this);
    tm = jtabOrders.getModel();
    tm.addTableModelListener(new TableModelListener() {
      public void tableChanged(TableModelEvent tme) {
        if (tme.getType() == TableModelEvent.UPDATE) {
          System.out.println("Cell " + tme.getFirstRow() + ", " + tme.getColumn() + " changed."
              + " The new value: " + tm.getValueAt(tme.getFirstRow(), tme.getColumn()));
        }
      }
    });
    jfrm.add(new JScrollPane(jtabOrders));
    jfrm.setVisible(true);
  }
  public void valueChanged(ListSelectionEvent le) {
    String str = "Selected Row(s): ";
    int[] rows = jtabOrders.getSelectedRows();
    for (int i = 0; i < rows.length; i++)
      str += rows[i] + " ";
    str += "Selected Column(s): ";
    int[] cols = jtabOrders.getSelectedColumns();
    for (int i = 0; i < cols.length; i++)
      str += cols[i] + " ";
    str += "Selected Cell: " + jtabOrders.getSelectedRow() + ", "
        + jtabOrders.getSelectedColumn();
    System.out.println(str);
  }
  public static void main(String args[]) {
    new Main();
  }
}





Row selection is enabled, Get the indices of the selected rows

import javax.swing.JTable;
public class Main {
  public static void main(String[] argv) throws Exception {
    JTable table = new JTable();
    if (!table.getColumnSelectionAllowed() && table.getRowSelectionAllowed()) {
      // 
      int[] rowIndices = table.getSelectedRows();
    }
  }
}





Toggles the selection state, if it were called again, it exactly reverses the first call.

import javax.swing.JTable;
import javax.swing.ListSelectionModel;
public class Main {
  public static void main(String[] argv) throws Exception {
    int rows = 10;
    int cols = 5;
    JTable table = new JTable(rows, cols);
    table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    table.setColumnSelectionAllowed(true);
    table.setRowSelectionAllowed(true);
    boolean toggle = true;
    boolean extend = false;
    table.changeSelection(1, 3, toggle, extend);
  }
}