JTable: selecting multiple cells

Supposing you have a spreadsheet layout with A,B,C on the columns and 1,2,3 on the rows, is it possible to allow the user to select cells A1 and C3, like they can in a normal spreadsheet app?
Somehow I need to obtain this kind of functionality from our system, although I have no idea how at present.

Something like.....
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TableExample extends JFrame {
   boolean[][] selectedCells = new boolean[5][5];
    public TableExample() {
       super("Table Selection Test");
       final JTable table = new JTable(5, 5) {
          public boolean isCellSelected(int row, int column) {
             return selectedCells[row][column];
       table.addMouseListener(new MouseAdapter() {
          public void mousePressed(MouseEvent e) {
             int row = table.rowAtPoint(e.getPoint());
             int column = table.columnAtPoint(e.getPoint());
             if (e.isControlDown()) {
                selectedCells[row][column] = !selectedCells[row][column];
             else {
                for (int i = 0 ; i < 5 ; i++) {
                   for (int j = 0 ; j < 5 ; j++) {
                      selectedCells[i][j] = false;
                selectedCells[row][column] = true;
             table.repaint();
      getContentPane().setLayout(new BorderLayout());
      getContentPane().add(new JScrollPane(table), BorderLayout.CENTER);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setSize(400, 400);
   public static void main(String[] args) {
      new TableExample().setVisible(true);
}

Similar Messages

  • How can I select multiple cells in tableview with javafx only by mouse?

    I have an application with a tableview in javafx and i want to select multiple cells only by mouse (something like the selection which exists in excel).I tried with setOnMouseDragged but i cant'n do something because the selection returns only the cell from where the selection started.Can someone help me?

    For mouse drag events to propagate to nodes other than the node in which the drag initiated, you need to activate a "full press-drag-release gesture" by calling startFullDrag(...) on the initial node. (See the Javadocs for MouseEvent and MouseDragEvent for details.) Then you can register for MouseDragEvents on the table cells in order to receive and process those events.
    Here's a simple example: the UI is not supposed to be ideal but it will give you the idea.
    import java.util.Arrays;
    import javafx.application.Application;
    import javafx.beans.property.SimpleStringProperty;
    import javafx.collections.FXCollections;
    import javafx.collections.ObservableList;
    import javafx.event.EventHandler;
    import javafx.geometry.Insets;
    import javafx.scene.Group;
    import javafx.scene.Scene;
    import javafx.scene.control.Label;
    import javafx.scene.control.SelectionMode;
    import javafx.scene.control.TableCell;
    import javafx.scene.control.TableColumn;
    import javafx.scene.control.TableView;
    import javafx.scene.control.cell.PropertyValueFactory;
    import javafx.scene.input.MouseDragEvent;
    import javafx.scene.input.MouseEvent;
    import javafx.scene.layout.VBox;
    import javafx.scene.text.Font;
    import javafx.stage.Stage;
    import javafx.util.Callback;
    public class DragSelectionTable extends Application {
        private TableView<Person> table = new TableView<Person>();
        private final ObservableList<Person> data =
            FXCollections.observableArrayList(
                new Person("Jacob", "Smith", "[email protected]"),
                new Person("Isabella", "Johnson", "[email protected]"),
                new Person("Ethan", "Williams", "[email protected]"),
                new Person("Emma", "Jones", "[email protected]"),
                new Person("Michael", "Brown", "[email protected]")
        public static void main(String[] args) {
            launch(args);
        @Override
        public void start(Stage stage) {
            Scene scene = new Scene(new Group());
            stage.setTitle("Table View Sample");
            stage.setWidth(450);
            stage.setHeight(500);
            final Label label = new Label("Address Book");
            label.setFont(new Font("Arial", 20));
            table.setEditable(true);
            TableColumn<Person, String> firstNameCol = new TableColumn<>("First Name");
            firstNameCol.setMinWidth(100);
            firstNameCol.setCellValueFactory(
                    new PropertyValueFactory<Person, String>("firstName"));
            TableColumn<Person, String> lastNameCol = new TableColumn<>("Last Name");
            lastNameCol.setMinWidth(100);
            lastNameCol.setCellValueFactory(
                    new PropertyValueFactory<Person, String>("lastName"));
            TableColumn<Person, String> emailCol = new TableColumn<>("Email");
            emailCol.setMinWidth(200);
            emailCol.setCellValueFactory(
                    new PropertyValueFactory<Person, String>("email"));
            final Callback<TableColumn<Person, String>, TableCell<Person, String>> cellFactory = new DragSelectionCellFactory();
            firstNameCol.setCellFactory(cellFactory);
            lastNameCol.setCellFactory(cellFactory);
            emailCol.setCellFactory(cellFactory);
            table.setItems(data);
            table.getColumns().addAll(Arrays.asList(firstNameCol, lastNameCol, emailCol));
            table.getSelectionModel().setCellSelectionEnabled(true);
            table.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
            final VBox vbox = new VBox();
            vbox.setSpacing(5);
            vbox.setPadding(new Insets(10, 0, 0, 10));
            vbox.getChildren().addAll(label, table);
            ((Group) scene.getRoot()).getChildren().addAll(vbox);
            stage.setScene(scene);
            stage.show();
        public static class DragSelectionCell extends TableCell<Person, String> {
            public DragSelectionCell() {
                setOnDragDetected(new EventHandler<MouseEvent>() {
                    @Override
                    public void handle(MouseEvent event) {
                        startFullDrag();
                        getTableColumn().getTableView().getSelectionModel().select(getIndex(), getTableColumn());
                setOnMouseDragEntered(new EventHandler<MouseDragEvent>() {
                    @Override
                    public void handle(MouseDragEvent event) {
                        getTableColumn().getTableView().getSelectionModel().select(getIndex(), getTableColumn());
            @Override
            public void updateItem(String item, boolean empty) {
                super.updateItem(item, empty);
                if (empty) {
                    setText(null);
                } else {
                    setText(item);
        public static class DragSelectionCellFactory implements Callback<TableColumn<Person, String>, TableCell<Person, String>> {
            @Override
            public TableCell<Person, String> call(final TableColumn<Person, String> col) {         
                return new DragSelectionCell();
        public static class Person {
            private final SimpleStringProperty firstName;
            private final SimpleStringProperty lastName;
            private final SimpleStringProperty email;
            private Person(String fName, String lName, String email) {
                this.firstName = new SimpleStringProperty(fName);
                this.lastName = new SimpleStringProperty(lName);
                this.email = new SimpleStringProperty(email);
            public String getFirstName() {
                return firstName.get();
            public void setFirstName(String fName) {
                firstName.set(fName);
            public String getLastName() {
                return lastName.get();
            public void setLastName(String fName) {
                lastName.set(fName);
            public String getEmail() {
                return email.get();
            public void setEmail(String fName) {
                email.set(fName);

  • How do i select multiple cells in numbers or iPad?

    Hello,
    can you help me? I do not find out how to select multiple cells in a table that do not stand next to each other.
    For example, I want to select cells A1, A3, A9 and so on. Afterwards I want to change the colour.
    Do you have an idea? Perhaps it's quite simple but I don't find the solution
    Sorry, I'm no native english speaker. I hope you'll understand what I am looking for.

    HI Ritscho
    I do not beleive this is possible, I can see other threads here from 2 years ago asking the same thing and none of them have answers.
    You can selesct a range of adjacent cells as Eric said, but not 2 different ranges. I usually use numbers on the iPad for filling in template spreadsheets that I create on my Mac. Most of the formatting I do on the Mac then fill in the blanks whilst i'm out and about.
    Not the answer you were looking for but hope it helps.

  • JTable - Programmatically selection multiple cells

    Hi!
    I'd like to know wether it's possible to programmatically select certain cells of a Jtable component.
    For example:
    My Jtable looks like that
    1 2 3
    4 5 6
    7 8 9
    and I want to select cell 2,4 and 7. How could I do that??
    Thanks for answers...

    Hello,
    I consciously read your thread, but I still can't get the sample code running.
    (java.lang.StackOverflowError
    Exception in thread "main" )
    Would you please give me a hint?
    Or better,
    send or post me the sample code of your class 'AttributiveCellTableModel', please.
    Thank you very much in advance!
    Thorsten

  • How do i select multiple cells in dreamweaver cc?

    Can't get cursor to appear to break and merge table cells. Keeps moving entire cell.
    Thanks,
    winifred

    in past version of dreamweaver I could see the cells and borders in design view and easily select multiples with a cursor. Just updated to CC and now only see blue boxes, arrow.
    Any thoughts on how to get a normal table view where I can select back.
    Any help is appreciated.
    winifred

  • Selecting multiple cells with keyboard command?

    Is there a way in Numbers to select many adjecent cells in a column without using the mouse? I have a document that has thousands of rows, so selecting 2000 cells in a column with the mouse for example, obviously takes forever. I would love to be able to give the command 'select A1 to A2000'

    Hi Jerry,
    I didn't want to select the full column, only part of it, like 2000 cells somewhere in the middle of 4000. But your tip made me play around with the Command and Shift keys and I figured out a way to do it. I selcted the full column, then I Command-clicked on the first cell I wanted to in my selection. That made a 'gap' in the selction. Now I went to the very top of the document and Shift-clicked on the first cell. Then all the cells above my first target cell was de-selected. Then I did the same thing and Command-clikced on the the last cell I wanted to highlight, and then went to the last cell of the document and used Shift-Click do deselect everything below the last cell I wanted to select.

  • Formula entry by selecting multiple cells

    I'm in my 30 day eval of iwork. In Numbers I don't see a way of entering a formula without spelling out the cell references into the cell containing the formula result.
    For example, in Excel, after selecting the cell for the result, in that cell I start the formula (=), then I select the first cell, then an operator , then the next cell, then another operator , etc., press enter, then the cell shows the result of the formula (sum in this example).
    The Numbers user manual did not offer a similar alternative. Is there a way to click on each cell reference to build the formula?
    Thanks much

    It seems that you didn't search carefully in the Users Guide.
    Page 89 everybody may read:
    +Adding Cell References to a Formula+
    +To insert a cell reference, _you can click a cell_, click a reference tab, or select a range of+
    +cells when there’s an insertion point in the text field of the Formula Editor or the+
    +Formula Bar. You can also insert a cell reference by typing it.+
    +When you insert a cell reference by selecting cells or reference tabs, Numbers adds cell+
    +references that use header cell names if “Use header cell names as references” is+
    +selected in the General pane of Numbers preferences.+
    +When you type a cell reference that includes the name of a header cell, table, or sheet,+
    +Numbers displays a list of suggestions that match what you’ve started to type. You can+
    +select from the list or continue typing.+
    Yvan KOENIG (from FRANCE samedi 19 juillet 2008 10:02:41)

  • Select Multiple cell

    HI experts,
         It‘s  possible to select Discontinuous cells in OO ALV report ? Like the picture in the attachment,  I want select all the cell in red box.

    Hi
    Please refer this link
    Selecting Cells, Rows and Columns (SAP Library - ALV Object Model
    Regards
    Arun VS

  • How to select multiple cells on a spreadsheet (online diary) without click and drag or shift and arrow keys as iPad has neither :(

    Hey guys really annoyed as I got my I pad with main reason of being able to update my online diary which is basically a spreadsheet, but I can't select more than one cell to book out a time slot, dragging just tees up the copy function and without arrow keys cannot shift and highlight, coming from windows wandering if this function is done another way on macs?  Any help would be appreciated as I'm thinking only way is to get the wireless keyboard which has arrow keys but kind of defeats the point of iPad.
    Thanks in advance ;)

    I guess I should state how much of a newbie I am.
    I did take a summer Java course at a community college this summer and I have some other programming experience (mostly Matlab).
    The course covered a lot of the language but it wasn't exhaustive. We covered (in no particular order) Arrays, Interfaces, overloading, inheritance, loops, actionlisteners, Layout managers, exceptions (a little) One thing that we really didn't get into were packages.
    We did some GUI design, but not a whole lot.
    The programming that I do with Matlab is very similar to C. (i.e. highly procedural not Object Oriented) so I think that's where some of my stumbling blocks are. I feel pretty comfortable reading Java code and using the API (sort of) but I didn't even know that 2D intersections existed.
    I have just started using eclipse last week. My previous coding was just done with textpad, so I am trying to get used to compiling code and building projects (and .jars) with an IDE.
    Thank you for the tips. I am going to keep looking around and see what I can find.

  • JTable - Select Individual Cell

    After the user has made an error entering data into a cell of a table I am displaying an error dialog and then I would like to move the user back to the cell in error (if he has hit tab) and have the cell selected.
    I have set :
    tbl.setColumnSelectionAllowed(false);
    tbl.setRowSelectionAllowed(false);
    The tried the following and many variations there of and it did not work:
    in method: public void setValueAt(Object value, int row, int col)
           if (col == 2) {
                            try{
                                loc1.setFrameLocation( (String) value);
                            catch (AppException e) {
                                ErrorDisplay.displayAppException(tblPhysicalProfile, "Cell Error " + getTitleText(), e);
                                tbl.changeSelection(row, col, false, false);
                        }The row and col is correct but no cell selection occurs

    I have different types of controls in the table and I only want this for specifc columnsYou can also assign editors to a specific class or column. Read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#validtext]How to Use Tables for an example of assigning an editor to a class. To assign an editor to a column you would get the TableColumnModel and then get the TableColumn and assign the editor.

  • Contiguous and non-contiguous multiple cell selection in JTable

    I desparately need your help on this.
    My appliaction contains a JTable. The users should be permitted to select multiple cells (both contiguous and non-contiguous) using
    Ctrl + Click -- add that cell the already existing selection
    Shift + Click -- add all cells in the range to the selection.
    I like to have the selection behaviour as that in Excel (where you could ctrl + click on any cell to add it to selection).
    Questions:
    ==========
    Is this behavior possible using JTable?
    How to do this?

    Hi, use
    JTable table = new JTable();
    DefaultListSelectionModel  dlm =  new DefaultListSelectionModel();
    dlm.setSelectionMode( ListSelectionModel.MULTIPLE_INTERVAL_SELECTION  ); //1( the first one should be the one you are looking for)
    or (choose 1 or 2, the rest stays the same)
    dlm.setSelectionMode( ListSelectionModel.SINGLE_INTERVAL_SELECTION );//2
    table.getColumnModel().setSelectionModel(dlm);
    table.setCellSelectionEnabled(true);Hope this helps.
    Greetings Michael.

  • Multiple Cell Selection in a JTable (again...)

    Hi All -
    I'm trying to get a JTable working well with the ability to select multiple cells in the way you'd expect to be able to (in Excel for example). By this I mean, hold down ctrl to add to a selection, hold shift to select between the last selection and the new one, be able to drag multiple regions with the mouse and have them be selected.
    I've seen lots of talk about this, for example on this thread:
    http://forum.java.sun.com/thread.jspa?threadID=619580&start=0&tstart=0
    (the code here will not work in the 'general' case, for example it doesn't really support dynamic table resizing)
    ...and found some pretty extensive code from here:
    http://www.codeguru.com/java/articles/663.shtml
    ...that kinda half works. (but the selection model is very strange once you get it running. Not at all what the average user would be used to)
    Does anyone have this working 100% with code they can share? It is very surprising to me that this is not the default behavior in Swing to be honest.
    I'm sure that I can come up with a solution for my situation, but I may as well not waste the time if someone already has something working for this.
    Thanks!

    If you have columnSelectionAllowed,rowselectionAllowed and cellSelectionEnabled then you can select cell by cell if you use the control key,
    Now the problem is, if you don't have input by your keyboard, in my case, I have a big table and I need to select diferent cells that match a certain criteria,
    jTable2.setRowSelectionInterval(j,j); //but this only works not for different rows 5 - 120 - 595
    I'm trying to use:
    jTable2.changeSelection()
    but still don't have good results....
    If any one could help to this matter will be really appreciated...
    thanks...

  • Multiple Cell Selection inJTable

    I want to select multiple cells ( 4 consequent cells) with single mouse click.The problem is the 4 cells are getting selected ,but the border is being set to only one cell on which i clicked,but the selection background color is set to all the four.
    i want the border to be included for all the four cells ,so that it looks like i have selected a set of cells .
    waiting for a reply.
    please help.

    In order to accomplish this, you will have to drastically modify the UI delegate for JTable. The difference between the areas you are speaking of is that one is the 'selection' and the one with the border is the 'focus' cell which represents the 'anchor' of the selection.
    The actual routines that paint the table cells are marked as private in the BasicTableUI class, so that is not a workable solution.
    Let this be a lesson to all Java programmers (ahem) about making critical methods private!
    Mitch

  • JTable select cells

    Hi,
    I have a JTable which is set individual cell selectable and allow multipleselection. I have a display problem when I use "CTRL" key and mouse toselect cells. The problem is that I cannot select them individually. (Someof Other cell are also selected) .
    Is it the behaviour of JTable?
    Could you tell me how can i select multiple "Cell Selection" from the JTable.
    For Example, you can find this feature in "MocroSoft Excel" (pressing "ctrl" key, select multiple cells)
    Thanks
    Nobi

    setSelectionMode
    public void setSelectionMode(int selectionMode)
    Sets the table's selection mode to allow only single selections, a single contiguous interval, or multiple intervals.
    Note: JTable provides all the methods for handling column and row selection. When setting states, such as setSelectionMode, it not only updates the mode for the row selection model but also sets similar values in the selection model of the columnModel. If you want to have the row and column selection models operating in different modes, set them both directly.
    Both the row and column selection models for JTable default to using a DefaultListSelectionModel so that JTable works the same way as the JList. See the setSelectionMode method in JList for details about the modes.

  • When selecting one cell, multiple cells highlight

    When I am working with Excel 2010, I try to select a single cell however multiple cells get highlighted. It will highlight usually the next 5-6 cells in the same row. It occurs randomly on random cells, but happens about 25% of the time. If I click the
    cell and it does its highlighting thing, I usually have to click away in another cell and then re-click the first one to get it to go away. Also, if I just try to ignore the highlighted cells and try to work as normal, when I try to tab to the next cell in
    the row, it will only let me tab between the cells in the column that are highlighted. It is not a mouse problem, I am not accidentally selecting multiple cells, and it happens on documents I created as well as documents others have created. It will also happens
    on a new, blank document or others completely stripped of any kind of potentially hidden formatting. I have not tried to re-install Office yet, but that will be next step if no one has a solution. Thanks

    I ran into this problem today working in Excel 2010 at 90% zoom.
    First I tried F8 and Shift+F8 but neither of them worked.
    Next I changed the zoom levels up and down and this worked while I was at a different zoom level than the document was saved in but went back to the same problem when I tried working at 90% zoom again.
    Finally I came across the fix mentioned below from July 2, 2012 that suggested switching from Normal View to Page and then to Print view and back to Normal and this worked!!! Thanks to all for your input below, you saved my Monday morning!
    LIST OF POSSIBLE FIXES:
    1. Try using the F8 and/or Shift+F8 [extend selection] to toggle back and forth.
    2. Change zoom level of your document up or down [this was only a temporary fix for me].
    3. Change page layout between Normal, Page Layout, and Page Break Preview (the 3 boxes at the bottom right hand corner of excel spreadsheet) then back to Normal.

Maybe you are looking for

  • How to display more than one data on the same page?

    Hello all, I have a question that is if I want to choose more one data on the same page and the data is selected from the same column. I.E I want to tick more than one boxes in the page but the data is selected from the same column.

  • Can't get rid of account icon photo in mail header area

    How can I get rid of the thumbnail photo icon in the mail header area when I send an e-mail in Mail? It is one of the supplied icons that is in system preferences for "accounts", to distinguish my account from my wife's on our iMac G5 (10.4.10). I re

  • IDOC to File Mapping problem.

    Hi all, I am working on IDOC to file scenario. Here I need to create CSV file for some fields of the IDOC. Actually flat file should contain around 65 comma separated fields irrespective (independent of the segment presence in the IDOC) of the existe

  • Help someone sharing my network?

    I have an airport network with a password. I have my imac on it and my daughters macbook. when I go to finder it doesn't show my network or shared stuff. it use too. I can't even see that my daughter is sharing my airport wireless. On her computer th

  • Starting up in Linux

    Hi am a newbie to linux and Oracle 9iAS. I have managed to install the application server and it all worked well. However on restarting the machine Oracle does not start up automatically. If anybody knows the scripts please let me know since I cant g