Example usage for javax.swing JTable setSelectionMode

List of usage examples for javax.swing JTable setSelectionMode

Introduction

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

Prototype

@BeanProperty(enumerationValues = { "ListSelectionModel.SINGLE_SELECTION",
        "ListSelectionModel.SINGLE_INTERVAL_SELECTION",
        "ListSelectionModel.MULTIPLE_INTERVAL_SELECTION" }, description = "The selection mode used by the row and column selection models.")
public void setSelectionMode(int selectionMode) 

Source Link

Document

Sets the table's selection mode to allow only single selections, a single contiguous interval, or multiple intervals.

Usage

From source file:interfaces.InterfazPrincipal.java

private void botonGenerarReporteClienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonGenerarReporteClienteActionPerformed
    // TODO add your handling code here:
    try {/*  w  ww.  j a v a 2s .co m*/
        if (clienteReporteClienteFechaFinal.getSelectedDate().getTime()
                .compareTo(clienteReporteClienteFechaInicial.getSelectedDate().getTime()) < 0) {
            JOptionPane.showMessageDialog(this, "La fecha final debe ser posterior al dia de inicio");
        } else {
            final ArrayList<Integer> listaIDFlujos = new ArrayList<>();
            final JDialog dialogoEditar = new JDialog();
            dialogoEditar.setTitle("Reporte cliente");
            dialogoEditar.setSize(350, 610);
            dialogoEditar.setResizable(false);

            JPanel panelDialogo = new JPanel();
            panelDialogo.setLayout(new GridBagLayout());

            GridBagConstraints c = new GridBagConstraints();
            //c.fill = GridBagConstraints.HORIZONTAL;

            JLabel ediitarTextoPrincipalDialogo = new JLabel("Informe cliente");
            c.gridx = 0;
            c.gridy = 0;
            c.gridwidth = 1;
            c.insets = new Insets(10, 45, 10, 10);
            Font textoGrande = new Font("Arial", 1, 18);
            ediitarTextoPrincipalDialogo.setFont(textoGrande);
            panelDialogo.add(ediitarTextoPrincipalDialogo, c);

            final JTable tablaDialogo = new JTable();
            DefaultTableModel modeloTabla = new DefaultTableModel() {

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

            modeloTabla.addColumn("Factura");
            modeloTabla.addColumn("Tipo Flujo");
            modeloTabla.addColumn("Fecha");
            modeloTabla.addColumn("Valor");

            //Llenar tabla
            ControladorFlujoFactura controladorFlujoFactura = new ControladorFlujoFactura();
            ArrayList<String[]> flujosCliente = controladorFlujoFactura.getTodosFlujo_Factura(
                    " where factura_id in (select factura_id from Factura where cliente_id = "
                            + String.valueOf(jTextFieldIdentificacionClienteReporte.getText())
                            + ") order by factura_id");
            // {"flujo_id","factura_id","tipo_flujo","fecha","valor"};
            ArrayList<Calendar> fechasFlujos = new ArrayList<>();

            for (int i = 0; i < flujosCliente.size(); i++) {
                String fila[] = new String[4];
                String[] objeto = flujosCliente.get(i);
                fila[0] = objeto[1];
                fila[1] = objeto[2];
                fila[2] = objeto[3];
                fila[3] = objeto[4];

                //Filtrar, mirar las fechas
                String[] partirEspacios = objeto[3].split("\\s");
                //El primer string es la fecha sin hora
                //Ahora esparamos por -
                String[] tomarAgeMesDia = partirEspacios[0].split("-");

                //Realizar filtro
                int ageConsulta = Integer.parseInt(tomarAgeMesDia[0]);
                int mesConsulta = Integer.parseInt(tomarAgeMesDia[1]);
                int diaConsulta = Integer.parseInt(tomarAgeMesDia[2]);

                //Obtenemos dias, mes y ao de la consulta
                //Inicial
                int anioInicial = clienteReporteClienteFechaFinal.getSelectedDate().get(Calendar.YEAR);
                int mesInicial = clienteReporteClienteFechaFinal.getSelectedDate().get(Calendar.MONTH) + 1;
                int diaInicial = clienteReporteClienteFechaFinal.getSelectedDate().get(Calendar.DAY_OF_MONTH);
                //Final
                int anioFinal = clienteReporteClienteFechaInicial.getSelectedDate().get(Calendar.YEAR);
                int mesFinal = clienteReporteClienteFechaInicial.getSelectedDate().get(Calendar.MONTH) + 1;
                int diaFinal = clienteReporteClienteFechaInicial.getSelectedDate().get(Calendar.DAY_OF_MONTH);

                //Construir fechas
                Calendar fechaDeLaBD = new GregorianCalendar(ageConsulta, mesConsulta, diaConsulta);
                //Set year, month, day)

                Calendar fechaInicialRango = new GregorianCalendar(anioInicial, mesInicial, diaInicial);
                Calendar fechaFinalRango = new GregorianCalendar(anioFinal, mesFinal, diaFinal);

                if (fechaDeLaBD.compareTo(fechaInicialRango) <= 0
                        && fechaDeLaBD.compareTo(fechaFinalRango) >= 0) {
                    fechasFlujos.add(fechaDeLaBD);
                    modeloTabla.addRow(fila);
                }

            }

            if (modeloTabla.getRowCount() > 0) {
                tablaDialogo.setModel(modeloTabla);
                tablaDialogo.getColumn("Factura").setMinWidth(80);
                tablaDialogo.getColumn("Tipo Flujo").setMinWidth(80);
                tablaDialogo.getColumn("Fecha").setMinWidth(90);
                tablaDialogo.getColumn("Valor").setMinWidth(80);
                tablaDialogo.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
                JScrollPane scroll = new JScrollPane(tablaDialogo);
                scroll.setPreferredSize(new Dimension(330, 150));

                c.gridx = 0;
                c.gridy = 1;
                c.gridwidth = 1;
                c.insets = new Insets(0, 0, 0, 0);
                panelDialogo.add(scroll, c);

                TimeSeries localTimeSeries = new TimeSeries("Compras del cliente en el periodo");

                Map listaAbonos = new HashMap();

                for (int i = 0; i < modeloTabla.getRowCount(); i++) {
                    listaIDFlujos.add(Integer.parseInt(flujosCliente.get(i)[0]));

                    if (modeloTabla.getValueAt(i, 1).equals("abono")) {
                        Calendar fechaFlujo = fechasFlujos.get(i);
                        double valor = Double.parseDouble(String.valueOf(modeloTabla.getValueAt(i, 3)));

                        int anoDato = fechaFlujo.get(Calendar.YEAR);
                        int mesDato = fechaFlujo.get(Calendar.MONTH) + 1;
                        int diaDato = fechaFlujo.get(Calendar.DAY_OF_MONTH);
                        Day FechaDato = new Day(diaDato, mesDato, anoDato);

                        if (listaAbonos.get(FechaDato) != null) {
                            double valorAbono = (double) listaAbonos.get(FechaDato);
                            listaAbonos.remove(FechaDato);
                            listaAbonos.put(FechaDato, valorAbono + valor);
                        } else {
                            listaAbonos.put(FechaDato, valor);

                        }

                    }

                }
                Double maximo = 0.0;
                Iterator iterator = listaAbonos.keySet().iterator();
                while (iterator.hasNext()) {
                    Day key = (Day) iterator.next();
                    Double value = (double) listaAbonos.get(key);
                    maximo = Math.max(maximo, value);
                    localTimeSeries.add(key, value);
                }

                //localTimeSeries.add();
                TimeSeriesCollection datos = new TimeSeriesCollection(localTimeSeries);

                JFreeChart chart = ChartFactory.createTimeSeriesChart("Compras del cliente en el periodo", // Title
                        "Tiempo", // x-axis Label
                        "Total ($)", // y-axis Label
                        datos, // Dataset
                        true, // Show Legend
                        true, // Use tooltips
                        false // Configure chart to generate URLs?
                );
                /*Altering the graph */
                XYPlot plot = (XYPlot) chart.getPlot();
                plot.setAxisOffset(new RectangleInsets(5.0, 10.0, 10.0, 5.0));
                plot.setDomainCrosshairVisible(true);
                plot.setRangeCrosshairVisible(true);

                XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer();
                renderer.setBaseShapesVisible(true);
                renderer.setBaseShapesFilled(true);

                NumberAxis numberAxis = (NumberAxis) plot.getRangeAxis();
                numberAxis.setRange(new Range(0, maximo * 1.2));
                Font font = new Font("Dialog", Font.PLAIN, 9);
                numberAxis.setTickLabelFont(font);
                numberAxis.setLabelFont(font);

                DateAxis axis = (DateAxis) plot.getDomainAxis();
                axis.setDateFormatOverride(new SimpleDateFormat("dd-MM-yyyy"));
                axis.setAutoTickUnitSelection(false);
                axis.setVerticalTickLabels(true);

                axis.setTickLabelFont(font);
                axis.setLabelFont(font);

                LegendTitle leyendaChart = chart.getLegend();
                leyendaChart.setItemFont(font);

                Font fontTitulo = new Font("Dialog", Font.BOLD, 12);
                TextTitle tituloChart = chart.getTitle();
                tituloChart.setFont(fontTitulo);

                ChartPanel CP = new ChartPanel(chart);
                Dimension D = new Dimension(330, 300);
                CP.setPreferredSize(D);
                CP.setVisible(true);
                c.gridx = 0;
                c.gridy = 2;
                c.gridwidth = 1;
                c.insets = new Insets(10, 0, 0, 0);
                panelDialogo.add(CP, c);

                c.gridx = 0;
                c.gridy = 3;
                c.gridwidth = 1;
                c.anchor = GridBagConstraints.WEST;
                c.insets = new Insets(10, 30, 0, 0);

                JButton botonCerrar = new JButton("Cerrar");
                botonCerrar.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        dialogoEditar.dispose();
                    }
                });
                panelDialogo.add(botonCerrar, c);

                JButton botonGenerarPDF = new JButton("Guardar archivo");
                botonGenerarPDF.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        ReporteFlujosCliente reporteFlujosCliente = new ReporteFlujosCliente();
                        reporteFlujosCliente.guardarDocumentoDialogo(dialogoEditar, listaIDFlujos,
                                Integer.parseInt(jTextFieldIdentificacionClienteReporte.getText()),
                                clienteReporteClienteFechaInicial.getSelectedDate(),
                                clienteReporteClienteFechaFinal.getSelectedDate());

                    }
                });
                c.insets = new Insets(10, 100, 0, 0);

                panelDialogo.add(botonGenerarPDF, c);

                JButton botonImprimir = new JButton("Imprimir");
                botonImprimir.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        ReporteFlujosCliente reporteFlujosCliente = new ReporteFlujosCliente();
                        reporteFlujosCliente.imprimirFlujo(listaIDFlujos,
                                Integer.parseInt(jTextFieldIdentificacionClienteReporte.getText()),
                                clienteReporteClienteFechaInicial.getSelectedDate(),
                                clienteReporteClienteFechaFinal.getSelectedDate());

                    }
                });
                c.insets = new Insets(10, 230, 0, 0);

                panelDialogo.add(botonImprimir, c);
                dialogoEditar.add(panelDialogo);

                dialogoEditar.setVisible(true);

            } else {
                JOptionPane.showMessageDialog(this,
                        "El cliente no registra movimientos en el rango de fechas seleccionado");
            }

        }
    } catch (Exception e) {
        JOptionPane.showMessageDialog(this, "Debe seleccionar un da inicial y final de fechas");
    }

}

From source file:nz.govt.natlib.ndha.manualdeposit.ManualDepositPresenter.java

private void setJobQueueTableDefaults(JTable jobQueueTable, JobQueueTableModel jobQueueTableModel) {
    jobQueueTableModel.addTableModelListener(new JobQueueTableModelListener());
    jobQueueTable.setModel(jobQueueTableModel);
    jobQueueTable.setSurrendersFocusOnKeystroke(true);
    jobQueueTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
    jobQueueTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    jobQueueTable.setColumnSelectionAllowed(true);
    jobQueueTable.setRowSelectionAllowed(true);
    TableRenderer renderer = new TableRenderer();
    TableColumn col = jobQueueTable.getColumnModel().getColumn(0);
    int width = 200;
    col.setPreferredWidth(width);/*from  w w  w .  j a  va2 s  . c o  m*/
    col.setWidth(width);
    col.setCellRenderer(renderer);

    col = jobQueueTable.getColumnModel().getColumn(1);
    width = 1400;
    col.setPreferredWidth(width);
    col.setWidth(width);
    col.setCellRenderer(renderer);
}

From source file:org.eclim.installer.step.EclipsePluginsStep.java

@Override
public void displayed() {
    setBusy(true);/*from w w w  .  ja  va  2  s  .  c  om*/
    setPreviousEnabled(false);

    try {
        overallLabel.setText("");
        overallProgress.setValue(0);
        taskLabel.setText("");
        taskProgress.setValue(0);
        taskProgress.setIndeterminate(true);

        // handle step re-entry.
        if (featuresPanel != null) {
            stepPanel.remove(featuresPanel);
        }

        EclipseInfo info = (EclipseInfo) Installer.getContext().getValue("eclipse.info");

        // find chosen features dependencies which need to be installed/upgraded.
        dependencies = unsatisfiedDependencies(info);

        if (dependencies.size() == 0) {
            overallProgress.setMaximum(1);
            overallProgress.setValue(1);
            overallLabel.setText("All third party plugins are up to date.");
            taskProgress.setMaximum(1);
            taskProgress.setValue(1);
            taskLabel.setText("");
        } else {
            tableModel = new DefaultTableModel();
            tableModel.addColumn("Feature");
            tableModel.addColumn("Version");
            tableModel.addColumn("Install / Upgrade");
            JTable table = new JTable(tableModel);
            table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            table.setDefaultRenderer(Object.class, new DependencyCellRenderer());
            table.getSelectionModel().addListSelectionListener(new DependencySelectionListener());

            featuresPanel = new JPanel(new BorderLayout());
            featuresPanel.setAlignmentX(0.0f);

            JPanel container = new JPanel(new BorderLayout());
            container.add(table, BorderLayout.CENTER);

            JScrollPane scrollPane = new JScrollPane(container);
            scrollPane.setAlignmentX(0.0f);

            availableFeatures = loadAvailableFeatures();
            for (Dependency dependency : dependencies) {
                String version = availableFeatures.get(dependency.getId());
                String manual = "";
                if (version == null) {
                    manual = " (Manual)";
                    version = dependency.getRequiredVersion();
                }
                tableModel.addRow(new Object[] { dependency.getId(), version,
                        (dependency.isUpgrade() ? "Upgrade" : "Install") + manual, });
            }

            JPanel buttons = new JPanel(new FlowLayout(FlowLayout.RIGHT, 0, 0));
            buttons.setAlignmentX(0.0f);

            JButton skipButton = new JButton(new SkipPluginsAction());
            JButton installButton = new JButton(new InstallPluginsAction(skipButton));

            buttons.add(installButton);
            buttons.add(skipButton);

            featuresPanel.add(scrollPane, BorderLayout.CENTER);
            featuresPanel.add(buttons, BorderLayout.SOUTH);

            stepPanel.add(featuresPanel);
            overallProgress.setValue(0);
            overallLabel.setText("");
            taskProgress.setValue(0);
            taskLabel.setText("");
        }
    } catch (Exception e) {
        setError(e);
    } finally {
        setValid(dependencies != null && dependencies.size() == 0);
        setBusy(false);
        setPreviousEnabled(true);
        taskProgress.setIndeterminate(false);
    }
}

From source file:org.formic.wizard.step.gui.FeatureListStep.java

/**
 * {@inheritDoc}//from   ww w  .  ja v a 2s. co  m
 * @see org.formic.wizard.step.GuiStep#init()
 */
public Component init() {
    featureInfo = new JEditorPane("text/html", StringUtils.EMPTY);
    featureInfo.setEditable(false);
    featureInfo.addHyperlinkListener(new HyperlinkListener());

    Feature[] features = provider.getFeatures();
    JTable table = new JTable(features.length, 1) {
        private static final long serialVersionUID = 1L;

        public Class getColumnClass(int column) {
            return getValueAt(0, column).getClass();
        }

        public boolean isCellEditable(int row, int column) {
            return false;
        }
    };
    table.setBackground(new javax.swing.JList().getBackground());

    GuiForm form = createForm();

    for (int ii = 0; ii < features.length; ii++) {
        final Feature feature = (Feature) features[ii];
        final JCheckBox box = new JCheckBox();

        String name = getName() + '.' + feature.getKey();
        form.bind(name, box);

        box.putClientProperty("feature", feature);
        featureMap.put(feature.getKey(), box);

        if (feature.getInfo() == null) {
            feature.setInfo(Installer.getString(getName() + "." + feature.getKey() + ".html"));
        }
        feature.addPropertyChangeListener(new PropertyChangeListener() {
            public void propertyChange(PropertyChangeEvent event) {
                if (Feature.ENABLED_PROPERTY.equals(event.getPropertyName())) {
                    if (box.isSelected() != feature.isEnabled()) {
                        box.setSelected(feature.isEnabled());
                    }
                }
            }
        });

        box.setText(Installer.getString(name));
        box.setBackground(table.getBackground());
        if (!feature.isAvailable()) {
            box.setSelected(false);
            box.setEnabled(false);
        }
        table.setValueAt(box, ii, 0);
    }

    FeatureListMouseListener mouseListener = new FeatureListMouseListener();
    for (int ii = 0; ii < features.length; ii++) {
        Feature feature = (Feature) features[ii];
        if (feature.isEnabled() && feature.isAvailable()) {
            JCheckBox box = (JCheckBox) featureMap.get(feature.getKey());
            box.setSelected(true);
            mouseListener.processDependencies(feature);
            mouseListener.processExclusives(feature);
        }
    }

    table.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    table.setShowHorizontalLines(false);
    table.setShowVerticalLines(false);
    table.setDefaultRenderer(JCheckBox.class, new ComponentTableCellRenderer());

    table.addKeyListener(new FeatureListKeyListener());
    table.addMouseListener(mouseListener);
    table.getSelectionModel().addListSelectionListener(new FeatureListSelectionListener(table));

    table.setRowSelectionInterval(0, 0);

    JPanel panel = new JPanel();
    panel.setLayout(new BorderLayout());
    JPanel container = new JPanel(new BorderLayout());
    container.add(table, BorderLayout.CENTER);
    panel.add(new JScrollPane(container), BorderLayout.CENTER);
    JScrollPane infoScroll = new JScrollPane(featureInfo);
    infoScroll.setMinimumSize(new Dimension(0, 50));
    infoScroll.setMaximumSize(new Dimension(0, 50));
    infoScroll.setPreferredSize(new Dimension(0, 50));
    panel.add(infoScroll, BorderLayout.SOUTH);

    return panel;
}

From source file:org.nuclos.client.ui.collect.result.ResultController.java

/**
 * TODO: Make this package visible again.
 *//*from  ww w  .  j  a v a2  s  .  c  o  m*/
public void setupResultPanel() {
    if (NuclosEntity.isNuclosEntity(getEntity().getName())) {
        this.getResultPanel().setActionsEnabled(false);
    }
    this.getResultPanel().addActionsVisibleListener(actionsVisibleListener);

    setupActions();

    // add selection listener for Result table:
    final JTable tblResult = this.getResultPanel().getResultTable();

    tblResult.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    tblResult.getSelectionModel().addListSelectionListener(newListSelectionListener(tblResult));

    this.getResultPanel().btnToggleSelectionMode.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            getResultPanel().setToggleSelection(!getResultPanel().isToggleSelection());
        }
    });
    this.getResultPanel().btnSelectAllRows.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (tblResult.getRowCount() > 0) {
                tblResult.getSelectionModel().setSelectionInterval(0, tblResult.getRowCount() - 1);
            }
        }
    });
    this.getResultPanel().btnDeSelectAllRows.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            tblResult.getSelectionModel().clearSelection();
        }
    });
    this.getResultPanel().addResultKeyListener(new ResultKeyListener() {
        @Override
        public boolean processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed) {
            if (e.getKeyCode() == ESC) {
                if (!pressed) {
                    tblResult.getSelectionModel().clearSelection();
                    return true;
                }
            } else if (e.getKeyCode() == UP || e.getKeyCode() == DOWN) {
                if (pressed) {
                    /* Warum wird dies bentigt?
                     * BasicTableUI.actionPerformed(...) sendet ein ungewolltes changeSelection mit toggle=false bei PFEIL-NACH-OBEN/-UNTEN (siehe unten).
                     * Der Standard in der Ergebnisansicht soll aber ein umgedrehtes Verhalten fr Mausklicks sein. (siehe Implementierung 
                     *       ResultPanel: super.changeSelection(rowIndex, columnIndex, alternateSelectionToggle? !toggle: toggle, extend);)  
                     * 
                     * else if (!inSelection) {
                          *       moveWithinTableRange(table, dx, dy);
                          *       table.changeSelection(leadRow, leadColumn, false, extend);
                         * }
                     */
                    getResultPanel().setAlternateSelectionToggle(false);
                    SwingUtilities.invokeLater(new Runnable() {
                        public void run() {
                            getResultPanel().setAlternateSelectionToggle(true);
                        }
                    });
                }
            }
            return false;
        }
    });

    // add mouse listener for double click in table:
    this.mouselistenerTableDblClick = new MouseAdapter() {

        private long lastClick = 0l;

        @Override
        public void mouseClicked(MouseEvent ev) {
            if (SwingUtilities.isLeftMouseButton(ev)) {
                if (lastClick + MainFrameTabbedPane.DOUBLE_CLICK_SPEED > System.currentTimeMillis()) {
                    int iRow = tblResult.rowAtPoint(ev.getPoint());
                    if (iRow >= 0 && iRow < tblResult.getRowCount()) {
                        tblResult.getSelectionModel().setSelectionInterval(iRow, iRow);
                        SwingUtilities.invokeLater(new Runnable() {
                            @Override
                            public void run() {
                                if (getSelectedCollectableFromTableModel() != null) {
                                    clctctl.cmdViewSelectedCollectables();
                                }
                            }
                        });
                    }
                }

                lastClick = System.currentTimeMillis();
            }
        }
    };
    getResultPanel().addDoubleClickMouseListener(this.mouselistenerTableDblClick);

    if (!SecurityCache.getInstance()
            .isActionAllowed(Actions.ACTION_WORKSPACE_CUSTOMIZE_ENTITY_AND_SUBFORM_COLUMNS)
            && getMainFrame().getWorkspace().isAssigned()) {
        getResultPanel().getResultTable().getTableHeader().setReorderingAllowed(false);
    }

    // change column ordering in table model when table columns are reordered by dragging a column with the mouse:
    getResultPanel().addColumnModelListener(newColumnModelListener());
    PreferencesUpdateListener pul = newResultTablePreferencesUpdateListener();
    getResultPanel().addColumnModelListener(pul);

    getResultPanel().addPopupMenuListener();
    getResultPanel().getSearchFilterBar().addEnabledListener(new ResetMainFilterEnabledListener());

    getResultPanel().setActionsVisible(
            getCollectController().getPreferences().getBoolean(RESULT_ACTIONS_VISIBLE, true));
}

From source file:org.revager.tools.GUITools.java

/**
 * Creates a new standard table./* w  w  w  .j  av a  2s .  c  o  m*/
 * 
 * @param model
 *            the table model
 * @param showHeader
 *            true if the header of the table should be visible
 * 
 * @return the newly created table
 */
@SuppressWarnings("serial")
public static JTable newStandardTable(TableModel model, boolean showHeader) {
    /*
     * Prep. for rollover
     */
    if (lastRolloverKey == Integer.MAX_VALUE) {
        lastRolloverKey = 0;
    } else {
        lastRolloverKey++;
    }

    final int keyIdx = lastRolloverKey;

    rollOverRowIndex.put(keyIdx, -1);

    final JTable table = new JTable(model) {

        @Override
        public boolean editCellAt(int row, int column, java.util.EventObject e) {
            boolean result = super.editCellAt(row, column, e);
            final Component editor = getEditorComponent();

            TableCellRenderer renderer = this.getColumnModel().getColumn(column).getCellRenderer();
            Font cellFont = null;
            if (renderer instanceof DefaultTableCellRenderer) {
                cellFont = ((DefaultTableCellRenderer) renderer).getFont();
            }
            if (editor != null && editor instanceof JTextComponent) {
                JTextComponent jTextComponent = (JTextComponent) editor;
                if (e == null) {
                    jTextComponent.selectAll();
                } else {
                    SwingUtilities.invokeLater(jTextComponent::selectAll);
                }
                jTextComponent.setBorder(UI.MARKED_BORDER_INLINE);
                if (cellFont != null) {
                    jTextComponent.setFont(cellFont);
                }
                editor.requestFocusInWindow();
            }
            return result;
        }

        @Override
        public TableCellRenderer getCellRenderer(int row, int column) {
            TableCellRenderer renderer = super.getCellRenderer(row, column);
            if (renderer instanceof DefaultTableCellRenderer) {
                ((DefaultTableCellRenderer) renderer).setBorder(new EmptyBorder(3, 3, 3, 3));
            }
            return renderer;
        }

        @Override
        public Component prepareRenderer(TableCellRenderer renderer, int row, int col) {
            Component comp = super.prepareRenderer(renderer, row, col);
            // Rollover
            comp.setBackground(getBackground());
            comp = super.prepareRenderer(renderer, row, col);
            if (!isRowSelected(row) && row == rollOverRowIndex.get(keyIdx)) {
                comp.setForeground(getForeground());
                comp.setBackground(UI.BLUE_BACKGROUND_COLOR);
            }

            // Tooltips
            JComponent jcomp = (JComponent) comp;
            if (renderer instanceof DefaultTableCellRenderer) {
                String toolTip = ((DefaultTableCellRenderer) renderer).getToolTipText();
                if (!StringUtils.isEmpty(toolTip)) {
                    jcomp.setToolTipText(toolTip);
                }
            }
            return comp;
        }
    };

    // Table properties
    table.setRowHeight(UI.TABLE_ROW_HEIGHT);
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    table.setShowGrid(false);
    table.setShowHorizontalLines(true);
    table.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));

    // Rollover
    MouseInputAdapter rolloverListener = new MouseInputAdapter() {
        @Override
        public void mouseExited(MouseEvent e) {
            rollOverRowIndex.put(keyIdx, -1);
            table.repaint();
        }

        @Override
        public void mouseMoved(MouseEvent e) {
            int row = table.rowAtPoint(e.getPoint());
            if (row != rollOverRowIndex.get(keyIdx)) {
                rollOverRowIndex.put(keyIdx, row);
                table.repaint();
            }
        }
    };
    table.addMouseMotionListener(rolloverListener);
    table.addMouseListener(rolloverListener);

    // Header
    if (!showHeader) {
        table.setTableHeader(null);
    }
    return table;
}

From source file:org.simmi.GeneSetHead.java

License:asdf

public List getSelspecContigs(List<JComponent> complist, final Map<String, List<Sequence>> speccontigMap,
        final String... selspec) {
    List<Sequence> contigs = null;
    final List<String> specs = new ArrayList<String>(speccontigMap.keySet());
    final JTable stable = new JTable();
    stable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    final TableModel stablemodel = new TableModel() {
        @Override/* w ww .j a v a  2 s. c o  m*/
        public int getRowCount() {
            return specs.size();
        }

        @Override
        public int getColumnCount() {
            return 1;
        }

        @Override
        public String getColumnName(int columnIndex) {
            return "Species";
        }

        @Override
        public Class<?> getColumnClass(int columnIndex) {
            return String.class;
        }

        @Override
        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return false;
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            if (rowIndex >= 0 && rowIndex < specs.size())
                return specs.get(rowIndex);
            return null;
        }

        @Override
        public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
        }

        @Override
        public void addTableModelListener(TableModelListener l) {
        }

        @Override
        public void removeTableModelListener(TableModelListener l) {
        }
    };
    stable.setModel(stablemodel);

    final JTable ctable = new JTable();
    ctable.setAutoCreateRowSorter(true);
    final TableModel ctablemodel = new TableModel() {
        @Override
        public int getRowCount() {
            int r = stable.getSelectedRow();
            String spec = selspec.length > 0 ? selspec[0] : (String) stable.getValueAt(r, 0);
            if (spec != null) {
                List<Sequence> contigs = geneset.speccontigMap.get(spec);
                return contigs.size();
            }
            return 0;
        }

        @Override
        public int getColumnCount() {
            return 1;
        }

        @Override
        public String getColumnName(int columnIndex) {
            return "Contigs";
        }

        @Override
        public Class<?> getColumnClass(int columnIndex) {
            return Sequence.class;
        }

        @Override
        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return false;
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            int r = stable.getSelectedRow();
            String spec = selspec.length > 0 ? selspec[0] : (String) stable.getValueAt(r, 0);
            List<Sequence> contigs = geneset.speccontigMap.get(spec);
            return contigs.get(rowIndex);
        }

        @Override
        public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
        }

        @Override
        public void addTableModelListener(TableModelListener l) {
        }

        @Override
        public void removeTableModelListener(TableModelListener l) {
        }
    };
    ctable.setModel(ctablemodel);

    JScrollPane sscrollpane = new JScrollPane(stable);
    JScrollPane cscrollpane = new JScrollPane(ctable);

    FlowLayout flowlayout = new FlowLayout();
    JComponent c = new JComponent() {
    };
    c.setLayout(flowlayout);
    if (selspec.length == 0)
        c.add(sscrollpane);
    c.add(cscrollpane);

    if (complist != null) {
        for (JComponent comp : complist) {
            c.add(comp);
        }
    }

    stable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent e) {
            ctable.tableChanged(new TableModelEvent(ctablemodel));
        }
    });
    JOptionPane.showMessageDialog(this, c);

    int[] rr = stable.getSelectedRows();
    if (rr.length > 1) {
        List slist = new ArrayList();
        for (int r : rr) {
            int i = stable.convertRowIndexToModel(r);
            slist.add(specs.get(i));
        }

        return slist;
    } else {
        int sr = stable.getSelectedRow();
        String spec = selspec.length > 0 ? selspec[0] : (String) stable.getValueAt(sr, 0);
        if (spec != null) {
            List<Sequence> ctgs = geneset.speccontigMap.get(spec);
            rr = ctable.getSelectedRows();
            contigs = new ArrayList<Sequence>();
            for (int r : rr) {
                int i = ctable.convertRowIndexToModel(r);
                contigs.add(ctgs.get(i));
            }
        }

        return contigs;
    }
}