Example usage for javax.swing JTable addMouseListener

List of usage examples for javax.swing JTable addMouseListener

Introduction

In this page you can find the example usage for javax.swing JTable addMouseListener.

Prototype

public synchronized void addMouseListener(MouseListener l) 

Source Link

Document

Adds the specified mouse listener to receive mouse events from this component.

Usage

From source file:com.haskins.cloudtrailviewer.sidebar.AbstractChart.java

private void addTable() {

    defaultTableModel.addColumn("");
    defaultTableModel.addColumn("Property");
    defaultTableModel.addColumn("Value");

    final LegendColourRenderer cellRenderer = new LegendColourRenderer();
    final JTable table = new JTable(defaultTableModel) {

        private static final long serialVersionUID = -6272711583089149891L;

        @Override/*from ww  w  .  jav  a2 s  .c  om*/
        public TableCellRenderer getCellRenderer(int row, int column) {
            if (column == 0) {
                return cellRenderer;
            }
            return super.getCellRenderer(row, column);
        }

        @Override
        public boolean isCellEditable(int row, int column) {
            return false;
        }
    };

    table.addMouseListener(new MouseAdapter() {

        @Override
        public void mousePressed(MouseEvent me) {

            JTable table = (JTable) me.getSource();
            String value = (String) defaultTableModel.getValueAt(table.getSelectedRow(), 1);

            if (me.getClickCount() == 2) {

                if (value.startsWith("i-")) {

                    Event event = null;
                    AllFilter filter = new AllFilter();
                    filter.setNeedle(value);
                    for (Event searchEvent : eventDb.getEvents()) {

                        if (filter.passesFilter(searchEvent)) {

                            event = searchEvent;
                            break;
                        }
                    }

                    if (event != null) {
                        AwsAccount account = AccountDao.getAccountByAcctNum(event.getRecipientAccountId());
                        ResourceDetailRequest request = new ResourceDetailRequest(account, event.getAwsRegion(),
                                "EC2 Instance", value);
                        ResourceDetailDialog.showDialog(CloudTrailViewer.frame, request);
                    }
                }

            } else if (me.getClickCount() == 1) {

                try {
                    eventTablePanel.setFilterString(value);
                } catch (Exception ex) {
                    LOGGER.log(Level.WARNING, "Problem responding to mouse event on chart table", ex);
                }
            }
        }
    });

    TableColumn column;
    for (int i = 0; i < 3; i++) {
        column = table.getColumnModel().getColumn(i);

        switch (i) {
        case 0:
            column.setMinWidth(15);
            column.setMaxWidth(15);
            column.setPreferredWidth(15);
            break;

        case 2:
            column.setMinWidth(70);
            column.setMaxWidth(70);
            column.setPreferredWidth(70);
            break;
        }
    }

    JScrollPane tablecrollPane = new JScrollPane(table);
    tablecrollPane.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));

    this.add(tablecrollPane, BorderLayout.CENTER);
}

From source file:org.zaproxy.zap.extension.multiFuzz.impl.http.HttpFuzzResultDialog.java

@Override
public JXTreeTable getTable() {
    if (table == null) {
        if (model == null) {
            model = new HttpFuzzTableModel();
        }//from  w  w w  .  j av  a 2  s.co  m
        table = new JXTreeTable(model);
        table.setDoubleBuffered(true);
        table.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        table.setName("HttpFuzzResultTable");
        table.setFont(new java.awt.Font("Default", java.awt.Font.PLAIN, 12));
        table.setDefaultRenderer(Pair.class, new IconTableCellRenderer());

        int[] widths = { 10, 25, 550, 30, 85, 55, 40, 70 };
        for (int i = 0, count = widths.length; i < count; i++) {
            TableColumn column = table.getColumnModel().getColumn(i);
            column.setPreferredWidth(widths[i]);
        }
        table.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mousePressed(java.awt.event.MouseEvent e) {
                showPopupMenuIfTriggered(e);
            }

            @Override
            public void mouseReleased(java.awt.event.MouseEvent e) {
                showPopupMenuIfTriggered(e);
            }

            private void showPopupMenuIfTriggered(java.awt.event.MouseEvent e) {
                if (e.isPopupTrigger()) {
                    if (e.isPopupTrigger()) {
                        // Select list item on right click
                        JTable table = (JTable) e.getSource();
                        int row = table.rowAtPoint(e.getPoint());

                        if (!table.isRowSelected(row)) {
                            table.changeSelection(row, 0, false, false);
                        }
                        View.getSingleton().getPopupMenu().show(e.getComponent(), e.getX(), e.getY());
                    }
                }
            }

        });
        table.getSelectionModel().addListSelectionListener(new javax.swing.event.ListSelectionListener() {

            @Override
            public void valueChanged(javax.swing.event.ListSelectionEvent e) {
                if (!e.getValueIsAdjusting()) {
                    if (table.getSelectedRowCount() == 0) {
                        return;
                    }
                    final int row = table.getSelectedRow();
                    if (getEntry(row) instanceof HttpFuzzRequestRecord) {
                        final HistoryReference historyReference = ((HttpFuzzRequestRecord) getEntry(row))
                                .getHistory();
                        try {
                            getMessageInspection().setMessage(historyReference.getHttpMessage());
                        } catch (HttpMalformedHeaderException | SQLException ex) {
                            logger.error(ex.getMessage(), ex);
                        }
                    }
                    updateValues();
                    redrawDiagrams();
                }
            }
        });
    }
    table.getTableHeader().addMouseListener(new MouseListener() {
        int sortedOn = -1;

        @Override
        public void mouseReleased(MouseEvent arg0) {
        }

        @Override
        public void mousePressed(MouseEvent arg0) {
        }

        @Override
        public void mouseExited(MouseEvent arg0) {
        }

        @Override
        public void mouseEntered(MouseEvent arg0) {
        }

        @Override
        public void mouseClicked(MouseEvent e) {
            int index = table.columnAtPoint(e.getPoint());
            List<HttpFuzzRecord> list = model.getEntries();
            if (list.size() == 0) {
                return;
            }
            HttpFuzzRecordComparator comp = new HttpFuzzRecordComparator();
            comp.setFeature(index);
            if (index == sortedOn) {
                Collections.sort(list, comp);
                Collections.reverse(list);
                sortedOn = -1;
            } else {
                Collections.sort(list, comp);
                sortedOn = index;
            }
            table.updateUI();
        }
    });
    table.setRootVisible(false);
    table.setVisible(true);
    return table;
}

From source file:net.pandoragames.far.ui.swing.FileListPanel.java

private void init(SwingConfig config, ComponentRepository componentRepository) {

    this.setLayout(new BorderLayout());

    this.setBorder(
            BorderFactory.createEmptyBorder(0, SwingConfig.PADDING, SwingConfig.PADDING, SwingConfig.PADDING));

    tableModel = componentRepository.getTableModel();
    componentRepository.getResetDispatcher().addResetable(tableModel);
    componentRepository.getSearchBaseListener().addResetable(tableModel);
    componentRepository.getUndoListener().setTableModel(tableModel);

    JTable fileListTable = componentRepository.getFileSetTable();
    int totalWidth = fileListTable.getPreferredSize().width;
    fileListTable.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
    fileListTable.setColumnSelectionAllowed(true);
    fileListTable.getTableHeader().addMouseListener(new TableHeaderMouseListener());
    fileListTable.getTableHeader().getColumnModel().getColumn(0)
            .setHeaderRenderer(new TableHeaderCheckBoxColumnRenderer());
    fileListPopupMenu = new FileListPopupMenu(fileListTable, tableModel, componentRepository, config);
    fileListTable.setComponentPopupMenu(fileListPopupMenu);
    fileListTable.addMouseListener(new FileViewOpener(fileListTable, componentRepository.getRootWindow(),
            config, componentRepository));
    fileListTable.getColumnModel().getColumn(0).setPreferredWidth(20);
    fileListTable.getColumnModel().getColumn(0).setMaxWidth(20);
    fileListTable.getColumnModel().getColumn(1).setCellRenderer(new TargetFileListTableCellRenderer());
    fileListTable.getColumnModel().getColumn(1).setPreferredWidth(2 * totalWidth / 5);
    fileListTable.getColumnModel().getColumn(2).setCellRenderer(new PathColumnRenderer());
    fileListTable.getColumnModel().getColumn(3).setCellRenderer(new InfoColumnRenderer(config));
    JScrollPane scrollPane = new JScrollPane(fileListTable);
    this.add(scrollPane, BorderLayout.CENTER);

    SelectCounter fileCounter = new SelectCounter();
    fileCounter.setBorder(BorderFactory.createEmptyBorder(1, SwingConfig.PADDING, 2, SwingConfig.PADDING));
    fileCounter.setForeground(Color.GRAY);
    ErrorCounter errorCounter = new ErrorCounter();
    errorCounter.setBorder(BorderFactory.createEmptyBorder(1, SwingConfig.PADDING, 2, SwingConfig.PADDING));
    JPanel counterLine = new JPanel();
    counterLine.setLayout(new BorderLayout());
    counterLine.add(fileCounter, BorderLayout.WEST);
    counterLine.add(errorCounter, BorderLayout.EAST);

    JProgressBar progressBar = new JProgressBar();
    progressBar.setEnabled(false);//from   w  w  w. java2s .co  m
    progressBar.setMaximumSize(new Dimension(100, 20));
    progressBar.setBorder(BorderFactory.createEmptyBorder(1, SwingConfig.PADDING, 2, SwingConfig.PADDING));
    componentRepository.getProgressBarUpdater().setProgressBar(progressBar);
    JPanel progressBarPanel = new JPanel();
    progressBarPanel.add(progressBar);
    counterLine.add(progressBarPanel, BorderLayout.CENTER);

    counterLine.setBorder(BorderFactory.createLineBorder(Color.GRAY, 1));
    this.add(counterLine, BorderLayout.SOUTH);

    tableModel.addTableModelListener(new ColumnCountListener(fileCounter));
    tableModel.addTableModelListener(errorCounter);
    componentRepository.getResetDispatcher().addResetable(fileCounter);
    componentRepository.getSearchBaseListener().addResetable(fileCounter);
    componentRepository.getOperationCallBackListener().addComponentStartReseted(fileCounter,
            OperationType.FIND);
    componentRepository.getResetDispatcher().addResetable(errorCounter);
    componentRepository.getSearchBaseListener().addResetable(errorCounter);

    viewAction = new ActionView(componentRepository, config);
}

From source file:io.heming.accountbook.ui.MainFrame.java

private void initTablePopupMenu() {
    JPopupMenu popupMenu = new JPopupMenu();

    JMenuItem deleteMenuItem = new JMenuItem("(D)",
            new ImageIcon(getClass().getResource("edit-delete-6.png")));
    deleteMenuItem.setMnemonic('D');
    popupMenu.add(deleteMenuItem);/*from  w  w  w. j  av  a2 s  .c  o m*/
    deleteMenuItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            deleteRecord();
        }
    });

    popupMenu.addSeparator();

    JMenuItem editMenuItem = new JMenuItem("(E)", new ImageIcon(getClass().getResource("edit-4.png")));
    editMenuItem.setMnemonic('E');
    popupMenu.add(editMenuItem);
    editMenuItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            Record record = model.getRecord(table.convertRowIndexToModel(table.getSelectedRow()));
            showUpdateRecordDialog(record);
        }
    });

    // ??popup menu
    table.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            if (disable)
                return;
            JTable table = (JTable) e.getSource();
            Point point = e.getPoint();
            int row = table.rowAtPoint(point);
            int col = table.columnAtPoint(e.getPoint());
            if (SwingUtilities.isRightMouseButton(e)) {
                if (row >= 0 && col >= 0) {
                    table.setRowSelectionInterval(row, row);
                }
                popupMenu.show(e.getComponent(), e.getX(), e.getY());
            } else if (SwingUtilities.isLeftMouseButton(e)) {
                if (e.getClickCount() == 2) {
                    if (row >= 0 && col >= 0) {
                        //                            Record record = model.getRecord(table.convertRowIndexToModel(row));
                        //                            showUpdateRecordDialog(record);
                    }
                }
            }
        }

    });

    table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
            .put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "Enter");
    table.getActionMap().put("Enter", new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent ae) {
            if (disable)
                return;
            //do something on JTable enter pressed
            int row = table.getSelectedRow();
            if (row >= 0) {
                Record record = model.getRecord(table.convertRowIndexToModel(row));
                showUpdateRecordDialog(record);
            }
        }
    });

}

From source file:de.wusel.partyplayer.gui.PartyPlayer.java

private Component createSongPanel() {
    final SongsTableModel model = new SongsTableModel(playerModel, settings, this);

    table = new JXTable(model) {

        @Override/* w w w .jav a2s.com*/
        public String getToolTipText(MouseEvent event) {
            int viewRowIndex = rowAtPoint(event.getPoint());
            if (viewRowIndex != -1) {
                int modelIndex = convertRowIndexToModel(viewRowIndex);
                SongWrapper songFromList = playerModel.getSongFromList(modelIndex);
                return songFromList.getFileName();
            }
            return super.getToolTipText(event);
        }
    };

    table.setAutoCreateRowSorter(true);
    String numberColumnName = getText("table.songs.column.number.label");
    table.getColumn(numberColumnName).setMaxWidth(25);
    table.getColumn(numberColumnName).setResizable(false);
    TableSortController sorter = (TableSortController) table.getRowSorter();
    sorter.setComparator(2, new SongComparator());

    table.getColumn(numberColumnName).setCellRenderer(new SubstanceDefaultTableCellRenderer() {

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                boolean hasFocus, int row, int column) {
            JLabel label = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row,
                    column);
            if (value != null)
                label.setText(((SongWrapper) value).getTrackNumber() + "");
            return label;
        }
    });

    table.getColumn(getText("table.songs.column.duration.label"))
            .setCellRenderer(new SubstanceDefaultTableCellRenderer() {

                @Override
                public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                        boolean hasFocus, int row, int column) {
                    JLabel label = (JLabel) super.getTableCellRendererComponent(table, value, isSelected,
                            hasFocus, row, column);
                    if (value != null)
                        label.setText(Util.getTimeString((Double) value));
                    return label;
                }
            });

    table.addMouseListener(new MouseAdapter() {

        @Override
        public void mouseClicked(MouseEvent e) {
            if (e.getClickCount() == 2) {
                addSongToPlaylist(
                        playerModel.getSongFromList(table.convertRowIndexToModel(table.getSelectedRow())));
            }
        }
    });

    table.addKeyListener(new KeyAdapter() {

        @Override
        public void keyPressed(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                addSongToPlaylist(
                        playerModel.getSongFromList(table.convertRowIndexToModel(table.getSelectedRow())));
            }
        }
    });

    JScrollPane scrollPane = new JScrollPane(table);
    table.setFillsViewportHeight(true);
    return scrollPane;
}

From source file:com.aw.swing.mvp.binding.component.BndSJTable.java

/**
 * Configure the grid columns based on the ColumnInfo information
 *///from   w w  w  .j av a  2s . co m
protected void configureColumns() {
    //jcv:2.0.1
    //        TableCellRenderer tableCellRenderer = createHeaderRenderer();
    JTableHeader jTableHeader = jTable.getTableHeader();
    TableCellRenderer tableCellRenderer = jTableHeader.getDefaultRenderer();
    for (int i = 0; i < columnsInfo.length; i++) {
        TableColumn col = jTable.getColumnModel().getColumn(i);
        if (columnsInfo[i] instanceof SelectorColumn) {
            final SelectorColumn selectorColumn = (SelectorColumn) columnsInfo[i];
            // Set special renderer for the column's header
            col.setHeaderRenderer(getSelectorHeaderRenderer(selectorColumn));
        } else {
            // Set special renderer for the column's header
            col.setHeaderRenderer(tableCellRenderer);
        }

        // set column width
        if (columnsInfo[i].getWidth() > 0) {
            col.setPreferredWidth(columnsInfo[i].getWidth());
        }
        if (columnsInfo[i].isEditable() || StringUtils.hasText(columnsInfo[i].getValidationRule())) {
            columnsInfo[i].initializeValidator();
        }
        // set column alignment if the cell is not editable
        if (!columnsInfo[i].isEditable() && !(columnsInfo[i] instanceof ButtonColumn)) {
            configureReadOnlyCell(col, columnsInfo[i]);
        } else {
            configureEditableCell(col, columnsInfo[i]);
        }
        columnsInfo[i].setIdx(i);
    }
    if (fixedColumns > 0) {
        fixedColumnTableMgr = FixedColumnTableDecorator.decorate(getJTable(), fixedColumns);
        JTable fixedTable = fixedColumnTableMgr.getFixedTable();
        JTableMouseProcessor jTableMouseProcessor = new JTableMouseProcessor(presenter, this, gridIndex);
        jTableMouseProcessor.setJTable(fixedTable);
        jTableMouseProcessor.setInFixedTable(true);
        fixedTable.addMouseListener(getJTableMouseListener(jTableMouseProcessor));
        fixedTable.getTableHeader().addMouseListener(getJTableHeaderMouseListener(jTableMouseProcessor));
    }
}

From source file:org.esa.snap.rcp.statistics.StatisticsPanel.java

private JPanel createStatPanel(Stx stx, final Mask mask) {
    final Histogram histogram = stx.getHistogram();

    XIntervalSeries histogramSeries = new XIntervalSeries("Histogram");
    int[] bins = histogram.getBins(0);
    for (int j = 0; j < bins.length; j++) {
        histogramSeries.add(histogram.getBinLowValue(0, j), histogram.getBinLowValue(0, j),
                j < bins.length - 1 ? histogram.getBinLowValue(0, j + 1) : histogram.getHighValue(0), bins[j]);
    }//ww w .  ja  v a2s .c  o m
    ChartPanel histogramPanel = createChartPanel(histogramSeries, "Value", "#Pixels", new Color(0, 0, 127));

    XIntervalSeries percentileSeries = new XIntervalSeries("Percentile");
    percentileSeries.add(0, 0, 1, histogram.getLowValue(0));
    for (int j = 1; j < 99; j++) {
        percentileSeries.add(j, j, j + 1, histogram.getPTileThreshold(j / 100.0)[0]);
    }
    percentileSeries.add(99, 99, 100, histogram.getHighValue(0));

    ChartPanel percentilePanel = createChartPanel(percentileSeries, "Percentile (%)", "Value Threshold",
            new Color(127, 0, 0));

    Object[][] tableData = new Object[][] { new Object[] { "#Pixels total:", histogram.getTotals()[0] },
            new Object[] { "Minimum:", stx.getMinimum() }, new Object[] { "Maximum:", stx.getMaximum() },
            new Object[] { "Mean:", stx.getMean() }, new Object[] { "Sigma:", stx.getStandardDeviation() },
            new Object[] { "Median:", stx.getMedian() },
            new Object[] { "Coef Variation:", stx.getCoefficientOfVariation() },
            new Object[] { "ENL:", stx.getEquivalentNumberOfLooks() },
            new Object[] { "P75 threshold:", histogram.getPTileThreshold(0.75)[0] },
            new Object[] { "P80 threshold:", histogram.getPTileThreshold(0.80)[0] },
            new Object[] { "P85 threshold:", histogram.getPTileThreshold(0.85)[0] },
            new Object[] { "P90 threshold:", histogram.getPTileThreshold(0.90)[0] },
            new Object[] { "Max error:", getBinSize(histogram) }, };

    JPanel plotContainerPanel = new JPanel(new GridLayout(1, 2));
    plotContainerPanel.add(histogramPanel);
    plotContainerPanel.add(percentilePanel);

    TableModel tableModel = new DefaultTableModel(tableData, new String[] { "Name", "Value" }) {
        @Override
        public Class<?> getColumnClass(int columnIndex) {
            return columnIndex == 0 ? String.class : Number.class;
        }

        @Override
        public boolean isCellEditable(int row, int column) {
            return false;
        }
    };

    final JTable table = new JTable(tableModel);
    table.setDefaultRenderer(Number.class, new DefaultTableCellRenderer() {
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                boolean hasFocus, int row, int column) {
            final Component label = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row,
                    column);
            if (value instanceof Float || value instanceof Double) {
                setHorizontalTextPosition(RIGHT);
                setText(getFormattedValue((Number) value));
            }
            return label;
        }

        private String getFormattedValue(Number value) {
            if (value.doubleValue() < 0.001 && value.doubleValue() > -0.001 && value.doubleValue() != 0.0) {
                return new DecimalFormat("0.####E0").format(value.doubleValue());
            }
            return String.format("%.4f", value.doubleValue());
        }
    });
    table.addMouseListener(popupHandler);

    JPanel textContainerPanel = new JPanel(new BorderLayout(2, 2));
    textContainerPanel.setBackground(Color.WHITE);
    textContainerPanel.add(table, BorderLayout.CENTER);

    JPanel statPanel = new JPanel(new BorderLayout(4, 4));
    statPanel.setBorder(new EmptyBorder(10, 2, 10, 2));
    statPanel.setBackground(Color.WHITE);
    statPanel.add(new JLabel(getSubPanelTitle(mask)), BorderLayout.NORTH);
    statPanel.add(textContainerPanel, BorderLayout.WEST);
    statPanel.add(plotContainerPanel, BorderLayout.CENTER);

    return statPanel;
}

From source file:SimpleTableSelectionDemo.java

public SimpleTableSelectionDemo() {
    super(new GridLayout(1, 0));

    final String[] columnNames = { "First Name", "Last Name", "Sport", "# of Years", "Vegetarian" };

    final Object[][] data = { { "Mary", "Campione", "Snowboarding", new Integer(5), new Boolean(false) },
            { "Alison", "Huml", "Rowing", new Integer(3), new Boolean(true) },
            { "Kathy", "Walrath", "Knitting", new Integer(2), new Boolean(false) },
            { "Sharon", "Zakhour", "Speed reading", new Integer(20), new Boolean(true) },
            { "Philip", "Milne", "Pool", new Integer(10), new Boolean(false) } };

    final JTable table = new JTable(data, columnNames);
    table.setPreferredScrollableViewportSize(new Dimension(500, 70));

    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    if (ALLOW_ROW_SELECTION) { // true by default
        ListSelectionModel rowSM = table.getSelectionModel();
        rowSM.addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
                //Ignore extra messages.
                if (e.getValueIsAdjusting())
                    return;

                ListSelectionModel lsm = (ListSelectionModel) e.getSource();
                if (lsm.isSelectionEmpty()) {
                    System.out.println("No rows are selected.");
                } else {
                    int selectedRow = lsm.getMinSelectionIndex();
                    System.out.println("Row " + selectedRow + " is now selected.");
                }// w w  w .j  av  a2 s .  c o  m
            }
        });
    } else {
        table.setRowSelectionAllowed(false);
    }

    if (ALLOW_COLUMN_SELECTION) { // false by default
        if (ALLOW_ROW_SELECTION) {
            //We allow both row and column selection, which
            //implies that we *really* want to allow individual
            //cell selection.
            table.setCellSelectionEnabled(true);
        }
        table.setColumnSelectionAllowed(true);
        ListSelectionModel colSM = table.getColumnModel().getSelectionModel();
        colSM.addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
                //Ignore extra messages.
                if (e.getValueIsAdjusting())
                    return;

                ListSelectionModel lsm = (ListSelectionModel) e.getSource();
                if (lsm.isSelectionEmpty()) {
                    System.out.println("No columns are selected.");
                } else {
                    int selectedCol = lsm.getMinSelectionIndex();
                    System.out.println("Column " + selectedCol + " is now selected.");
                }
            }
        });
    }

    if (DEBUG) {
        table.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                printDebugData(table);
            }
        });
    }

    //Create the scroll pane and add the table to it.
    JScrollPane scrollPane = new JScrollPane(table);

    //Add the scroll pane to this panel.
    add(scrollPane);
}

From source file:components.SimpleTableSelectionDemo.java

public SimpleTableSelectionDemo() {
    super(new GridLayout(1, 0));

    final String[] columnNames = { "First Name", "Last Name", "Sport", "# of Years", "Vegetarian" };

    final Object[][] data = { { "Kathy", "Smith", "Snowboarding", new Integer(5), new Boolean(false) },
            { "John", "Doe", "Rowing", new Integer(3), new Boolean(true) },
            { "Sue", "Black", "Knitting", new Integer(2), new Boolean(false) },
            { "Jane", "White", "Speed reading", new Integer(20), new Boolean(true) },
            { "Joe", "Brown", "Pool", new Integer(10), new Boolean(false) } };

    final JTable table = new JTable(data, columnNames);
    table.setPreferredScrollableViewportSize(new Dimension(500, 70));
    table.setFillsViewportHeight(true);// w  w w .  j  av  a2  s .  c om

    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    if (ALLOW_ROW_SELECTION) { // true by default
        ListSelectionModel rowSM = table.getSelectionModel();
        rowSM.addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
                //Ignore extra messages.
                if (e.getValueIsAdjusting())
                    return;

                ListSelectionModel lsm = (ListSelectionModel) e.getSource();
                if (lsm.isSelectionEmpty()) {
                    System.out.println("No rows are selected.");
                } else {
                    int selectedRow = lsm.getMinSelectionIndex();
                    System.out.println("Row " + selectedRow + " is now selected.");
                }
            }
        });
    } else {
        table.setRowSelectionAllowed(false);
    }

    if (ALLOW_COLUMN_SELECTION) { // false by default
        if (ALLOW_ROW_SELECTION) {
            //We allow both row and column selection, which
            //implies that we *really* want to allow individual
            //cell selection.
            table.setCellSelectionEnabled(true);
        }
        table.setColumnSelectionAllowed(true);
        ListSelectionModel colSM = table.getColumnModel().getSelectionModel();
        colSM.addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
                //Ignore extra messages.
                if (e.getValueIsAdjusting())
                    return;

                ListSelectionModel lsm = (ListSelectionModel) e.getSource();
                if (lsm.isSelectionEmpty()) {
                    System.out.println("No columns are selected.");
                } else {
                    int selectedCol = lsm.getMinSelectionIndex();
                    System.out.println("Column " + selectedCol + " is now selected.");
                }
            }
        });
    }

    if (DEBUG) {
        table.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                printDebugData(table);
            }
        });
    }

    //Create the scroll pane and add the table to it.
    JScrollPane scrollPane = new JScrollPane(table);

    //Add the scroll pane to this panel.
    add(scrollPane);
}

From source file:Main.java

public Main() {
    super(new GridLayout(1, 0));

    final String[] columnNames = { "First Name", "Last Name", "Sport", "# of Years", "Vegetarian" };

    final Object[][] data = { { "Mary", "Campione", "Snowboarding", new Integer(5), new Boolean(false) },
            { "Alison", "Huml", "Rowing", new Integer(3), new Boolean(true) },
            { "Kathy", "Walrath", "Knitting", new Integer(2), new Boolean(false) },
            { "Sharon", "Zakhour", "Speed reading", new Integer(20), new Boolean(true) },
            { "Philip", "Milne", "Pool", new Integer(10), new Boolean(false) } };

    final JTable table = new JTable(data, columnNames);
    table.setPreferredScrollableViewportSize(new Dimension(500, 70));
    table.setFillsViewportHeight(true);/*w w  w  . j  av  a2s  .  c o  m*/

    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    if (ALLOW_ROW_SELECTION) { // true by default
        ListSelectionModel rowSM = table.getSelectionModel();
        rowSM.addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
                // Ignore extra messages.
                if (e.getValueIsAdjusting())
                    return;

                ListSelectionModel lsm = (ListSelectionModel) e.getSource();
                if (lsm.isSelectionEmpty()) {
                    System.out.println("No rows are selected.");
                } else {
                    int selectedRow = lsm.getMinSelectionIndex();
                    System.out.println("Row " + selectedRow + " is now selected.");
                }
            }
        });
    } else {
        table.setRowSelectionAllowed(false);
    }

    if (ALLOW_COLUMN_SELECTION) { // false by default
        if (ALLOW_ROW_SELECTION) {
            // We allow both row and column selection, which
            // implies that we *really* want to allow individual
            // cell selection.
            table.setCellSelectionEnabled(true);
        }
        table.setColumnSelectionAllowed(true);
        ListSelectionModel colSM = table.getColumnModel().getSelectionModel();
        colSM.addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
                // Ignore extra messages.
                if (e.getValueIsAdjusting())
                    return;

                ListSelectionModel lsm = (ListSelectionModel) e.getSource();
                if (lsm.isSelectionEmpty()) {
                    System.out.println("No columns are selected.");
                } else {
                    int selectedCol = lsm.getMinSelectionIndex();
                    System.out.println("Column " + selectedCol + " is now selected.");
                }
            }
        });
    }

    if (DEBUG) {
        table.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                printDebugData(table);
            }
        });
    }

    // Create the scroll pane and add the table to it.
    JScrollPane scrollPane = new JScrollPane(table);

    // Add the scroll pane to this panel.
    add(scrollPane);
}