Example usage for javax.swing JTable getSelectedRow

List of usage examples for javax.swing JTable getSelectedRow

Introduction

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

Prototype

@BeanProperty(bound = false)
public int getSelectedRow() 

Source Link

Document

Returns the index of the first selected row, -1 if no row is selected.

Usage

From source file:jp.massbank.spectrumsearch.SearchPage.java

/**
 * ??//from  w  w  w.  j av a2 s  . c  o  m
 */
private void updateSelectQueryTable(JTable tbl) {

    // ?
    this.setCursor(waitCursor);

    int selRow = tbl.getSelectedRow();
    if (selRow >= 0) {
        tbl.clearSelection();
        Color defColor = tbl.getSelectionBackground();
        tbl.setRowSelectionInterval(selRow, selRow);
        tbl.setSelectionBackground(Color.PINK);
        tbl.update(tbl.getGraphics());
        tbl.setSelectionBackground(defColor);
    }
    // ?
    this.setCursor(Cursor.getDefaultCursor());
}

From source file:de.codesourcery.eve.skills.ui.components.impl.AssetListComponent.java

@Override
protected JPanel createPanel() {

    // Merge controls.
    final JPanel mergeControlsPanel = new JPanel();
    mergeControlsPanel.setLayout(new GridBagLayout());
    mergeControlsPanel.setBorder(BorderFactory.createTitledBorder("Merging"));

    int y = 0;//from   ww  w .  j  a  v a 2  s . c  o m

    // merge by type
    mergeAssetsByType.setSelected(true);
    mergeAssetsByType.addActionListener(actionListener);

    mergeControlsPanel.add(mergeAssetsByType, constraints(0, y).anchorWest().end());
    mergeControlsPanel.add(new JLabel("Merge assets by type", SwingConstants.LEFT),
            constraints(1, y++).width(2).end());

    // "ignore different packaging"
    ignorePackaging.setSelected(true);
    ignorePackaging.addActionListener(actionListener);

    mergeControlsPanel.add(new JLabel(""), constraints(0, y).anchorWest().end());
    mergeControlsPanel.add(ignorePackaging, constraints(1, y).anchorWest().end());
    final JLabel label1 = new JLabel("Merge different packaging", SwingConstants.RIGHT);
    mergeControlsPanel.add(label1, constraints(2, y++).end());

    // "ignore different locations"
    ignoreLocations.setSelected(true);
    ignoreLocations.addActionListener(actionListener);

    mergeControlsPanel.add(new JLabel(""), constraints(0, y).anchorWest().end());
    mergeControlsPanel.add(ignoreLocations, constraints(1, y).anchorWest().end());
    final JLabel label2 = new JLabel("Merge different locations", SwingConstants.RIGHT);
    mergeControlsPanel.add(label2, constraints(2, y++).end());

    linkComponentEnabledStates(mergeAssetsByType, ignoreLocations, ignorePackaging, label1, label2);

    /*
     * Filter controls.
     */

    final JPanel filterControlsPanel = new JPanel();
    filterControlsPanel.setLayout(new GridBagLayout());
    filterControlsPanel.setBorder(BorderFactory.createTitledBorder("Filters"));

    y = 0;
    // filter by location combo box
    filterByLocation.addActionListener(actionListener);
    locationComboBox.addActionListener(actionListener);

    filterByLocation.setSelected(false);
    linkComponentEnabledStates(filterByLocation, locationComboBox);

    locationComboBox.setRenderer(new LocationRenderer());
    locationComboBox.setPreferredSize(new Dimension(150, 20));
    locationComboBox.setModel(locationModel);

    filterControlsPanel.add(filterByLocation, constraints(0, y).end());
    filterControlsPanel.add(locationComboBox, constraints(1, y++).end());

    // filter by type combo box
    filterByType.addActionListener(actionListener);
    typeComboBox.addActionListener(actionListener);

    filterByType.setSelected(false);

    linkComponentEnabledStates(filterByType, typeComboBox);

    typeComboBox.setPreferredSize(new Dimension(150, 20));
    typeComboBox.setModel(typeModel);

    filterControlsPanel.add(filterByType, constraints(0, y).end());
    filterControlsPanel.add(typeComboBox, constraints(1, y++).end());

    // filter by item category combobox
    filterByCategory.addActionListener(actionListener);
    categoryComboBox.addActionListener(actionListener);
    categoryComboBox.setRenderer(new DefaultListCellRenderer() {

        @Override
        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
                boolean cellHasFocus) {

            super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);

            setText(getDisplayName((InventoryCategory) value));
            setEnabled(categoryComboBox.isEnabled());
            return this;
        }
    });

    filterByCategory.setSelected(false);
    linkComponentEnabledStates(filterByCategory, categoryComboBox);

    categoryComboBox.setPreferredSize(new Dimension(150, 20));
    categoryComboBox.setModel(categoryModel);

    filterControlsPanel.add(filterByCategory, constraints(0, y).end());
    filterControlsPanel.add(categoryComboBox, constraints(1, y++).end());

    // filter by item group combobox
    filterByGroup.addActionListener(actionListener);
    groupComboBox.addActionListener(actionListener);

    filterByGroup.setSelected(false);

    linkComponentEnabledStates(filterByGroup, groupComboBox);

    groupComboBox.setPreferredSize(new Dimension(150, 20));
    groupComboBox.setModel(groupModel);

    filterControlsPanel.add(filterByGroup, constraints(0, y).end());
    filterControlsPanel.add(groupComboBox, constraints(1, y++).end());

    /*
     * Table panel.
     */

    table = new JTable() {

        @Override
        public TableCellRenderer getCellRenderer(int row, int column) {

            // subclassing hack is needed because table
            // returns different renderes depending on column type
            final TableCellRenderer result = super.getCellRenderer(row, column);

            return new TableCellRenderer() {

                @Override
                public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                        boolean hasFocus, int row, int column) {

                    final Component comp = result.getTableCellRendererComponent(table, value, isSelected,
                            hasFocus, row, column);

                    final int modelRow = table.convertRowIndexToModel(row);
                    final Asset asset = model.getRow(modelRow);

                    final StringBuilder label = new StringBuilder("<HTML><BODY>");
                    label.append(asset.getItemId() + " - flags: " + asset.getFlags() + "<BR>");
                    if (asset.hasMultipleLocations()) {
                        label.append("<BR>");
                        for (ILocation loc : asset.getLocations()) {
                            label.append(loc.getDisplayName()).append("<BR>");
                        }
                    }

                    label.append("</BODY></HTML>");
                    ((JComponent) comp).setToolTipText(label.toString());

                    return comp;
                }
            };
        }
    };

    model.setViewFilter(this.viewFilter);

    table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

        @Override
        public void valueChanged(ListSelectionEvent e) {
            updateSelectedVolume();
        }
    });

    FixedBooleanTableCellRenderer.attach(table);
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    table.setModel(model);
    table.setBorder(BorderFactory.createLineBorder(Color.BLACK));
    table.setRowSorter(model.getRowSorter());

    popupMenuBuilder.addItem("Refine...", new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent e) {
            final List<Asset> assets = getSelectedAssets();
            if (assets == null || assets.isEmpty()) {
                return;
            }

            final ICharacter c = selectionProvider.getSelectedItem();
            final RefiningComponent comp = new RefiningComponent(c);
            comp.setItemsToRefine(assets);
            ComponentWrapper.wrapComponent("Refining", comp).setVisible(true);
        }

        @Override
        public boolean isEnabled() {
            return table.getSelectedRow() != -1;
        }
    });

    popupMenuBuilder.addItem("Copy selection to clipboard (text)", new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent e) {
            final List<Asset> assets = getSelectedAssets();
            if (assets == null || assets.isEmpty()) {
                return;
            }

            new PlainTextTransferable(toPlainText(assets)).putOnClipboard();
        }

        @Override
        public boolean isEnabled() {
            return table.getSelectedRow() != -1;
        }
    });

    popupMenuBuilder.addItem("Copy selection to clipboard (CSV)", new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent e) {
            final List<Asset> assets = getSelectedAssets();
            if (assets == null || assets.isEmpty()) {
                return;
            }

            final Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();

            clipboard.setContents(new PlainTextTransferable(toCsv(assets)), null);
        }

        @Override
        public boolean isEnabled() {
            return table.getSelectedRow() != -1;
        }
    });

    table.getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    this.popupMenuBuilder.attach(table);

    final JScrollPane scrollPane = new JScrollPane(table);

    /*
     * Name filter
     */

    final JPanel nameFilterPanel = new JPanel();
    nameFilterPanel.setLayout(new GridBagLayout());
    nameFilterPanel.setBorder(BorderFactory.createTitledBorder("Filter by name"));
    nameFilterPanel.setPreferredSize(new Dimension(150, 70));
    nameFilter.setColumns(10);
    nameFilter.getDocument().addDocumentListener(new DocumentListener() {

        @Override
        public void changedUpdate(DocumentEvent e) {
            model.viewFilterChanged();
        }

        @Override
        public void insertUpdate(DocumentEvent e) {
            model.viewFilterChanged();
        }

        @Override
        public void removeUpdate(DocumentEvent e) {
            model.viewFilterChanged();
        }
    });

    nameFilterPanel.add(nameFilter, constraints(0, 0).resizeHorizontally().end());
    final JButton clearButton = new JButton("Clear");
    clearButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            nameFilter.setText(null);
        }
    });
    nameFilterPanel.add(clearButton, constraints(1, 0).noResizing().end());

    // Selected volume
    final JPanel selectedVolumePanel = this.selectedVolume.getPanel();

    // add control panels to result panel
    final JPanel topPanel = new JPanel();
    topPanel.setLayout(new GridBagLayout());

    topPanel.add(mergeControlsPanel, constraints(0, 0).height(2).weightX(0).anchorWest().end());
    topPanel.add(filterControlsPanel, constraints(1, 0).height(2).anchorWest().weightX(0).end());
    topPanel.add(nameFilterPanel, constraints(2, 0).height(1).anchorWest().useRemainingWidth().end());
    topPanel.add(selectedVolumePanel, constraints(2, 1).height(1).anchorWest().useRemainingWidth().end());

    final JSplitPane splitPane = new ImprovedSplitPane(JSplitPane.VERTICAL_SPLIT, topPanel, scrollPane);

    splitPane.setDividerLocation(0.3d);

    final JPanel content = new JPanel();
    content.setLayout(new GridBagLayout());
    content.add(splitPane, constraints().resizeBoth().useRemainingSpace().end());

    return content;
}

From source file:interfaces.InterfazPrincipal.java

private void botonBuscarClienteCrearFacturaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonBuscarClienteCrearFacturaActionPerformed

    String nombre = nombreClienteCrearFactura.getText();
    String identificacion = IdentificacionClienteBuscarFactura.getText();

    ControladorCliente controladorCliente = new ControladorCliente();

    try {//from   w  w  w.  jav a2  s. co  m
        int id = 0;
        if (!identificacion.equals("")) {
            id = Integer.parseInt(identificacion);
        }

        ArrayList<Cliente> listaClientes = controladorCliente.obtenerClientes(nombre, id);

        if (listaClientes.isEmpty()) {
            mensajesBusquedaClientesFactura.setText("La busqueda no arrojo resultados");
            return;
        }

        final JDialog dialogoEditar = new JDialog(this);
        dialogoEditar.setTitle("Buscar clientes");
        dialogoEditar.setSize(600, 310);
        dialogoEditar.setResizable(false);

        JPanel panelDialogo = new JPanel();

        panelDialogo.setLayout(new GridBagLayout());

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

        JLabel editarTextoPrincipalDialogo = new JLabel("Buscar Cliente");
        c.gridx = 0;
        c.gridy = 0;
        c.gridwidth = 4;
        c.insets = new Insets(15, 200, 40, 0);
        c.ipadx = 100;
        Font textoGrande = new Font("Arial", 1, 18);
        editarTextoPrincipalDialogo.setFont(textoGrande);
        panelDialogo.add(editarTextoPrincipalDialogo, c);

        /*Vector col = new Vector();
         col.add("1");
         col.add("2");
         col.add("3");
         col.add("4");
         Vector row = new Vector();
                
         for (int i = 0; i < listaClientes.size(); i++) {
         Cliente cliente = listaClientes.get(i);
         Vector temp = new Vector();
         temp.add((i + 1) + "");
         temp.add(cliente.getNombre());
         temp.add(cliente.getCliente_id() + "");
         temp.add(cliente.getMonto_prestamo() + "");
         System.out.println("info" + cliente.getNombre() + "," + cliente.getMonto_prestamo());
         row.add(temp);
         }
                
         final JTable table = new JTable(row, col);         */
        final JTable table = new JTable();
        DefaultTableModel modeloTabla = new DefaultTableModel() {

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

        modeloTabla.addColumn("Numero");
        modeloTabla.addColumn("Identificacin");
        modeloTabla.addColumn("Nombre");
        modeloTabla.addColumn("Monto Prestamo");

        //LLenar tabla
        for (int i = 0; i < listaClientes.size(); i++) {
            Object[] data = { "1", "2", "3", "4" };
            data[0] = (i + 1);
            data[1] = listaClientes.get(i).getCliente_id();
            data[2] = listaClientes.get(i).getNombre();
            data[3] = listaClientes.get(i).getMonto_prestamo();

            modeloTabla.addRow(data);
        }

        table.setModel(modeloTabla);
        table.getColumn("Numero").setMinWidth(50);
        table.getColumn("Identificacin").setMinWidth(50);
        table.getColumn("Nombre").setMinWidth(110);
        table.getColumn("Monto Prestamo").setMinWidth(110);

        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        JScrollPane scroll = new JScrollPane(table);
        scroll.setPreferredSize(new Dimension(320, 150));

        table.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                jTextField_Factura_Cliente_Id.setText(table.getValueAt(table.getSelectedRow(), 1).toString());
                String identificacion = table.getValueAt(table.getSelectedRow(), 3).toString();
                ControladorFlujoFactura controladorFlujoFactura = new ControladorFlujoFactura();

                //SELECT * FROM Flujo_Factura where factura_id in (select factura_id from Factura where cliente_id = 1130614506);
                ArrayList<String[]> flujosCliente = controladorFlujoFactura.getTodosFlujo_Factura(
                        " where factura_id in (select factura_id from Factura where cliente_id = "
                                + String.valueOf(identificacion)
                                + " and estado=\"fiado\") order by factura_id");
                double pago = 0.0;

                for (int i = 0; i < flujosCliente.size(); i++) {
                    String[] datos = flujosCliente.get(i);
                    Object[] rowData = { datos[1], datos[2], datos[3], datos[4] };

                    if (datos[2].equals("deuda")) {
                        pago += Double.parseDouble(datos[4]);
                    } else {
                        pago -= Double.parseDouble(datos[4]);
                    }

                }
                nombreClienteCrearFactura.setText(table.getValueAt(table.getSelectedRow(), 2).toString());
                IdentificacionClienteBuscarFactura
                        .setText(table.getValueAt(table.getSelectedRow(), 1).toString());
                double montoPrestamo = Double
                        .parseDouble(table.getValueAt(table.getSelectedRow(), 3).toString());
                Double totalDisponible = montoPrestamo - pago;
                valorActualPrestamo.setText(String.valueOf(totalDisponible));
                //System.out.println(table.getValueAt(table.getSelectedRow(), 3).toString());
                botonAgregarProducto.setEnabled(true);
                botonGuardarFactura.setEnabled(true);
                botonEstablecerMontoFactura.setEnabled(true);
                dialogoEditar.dispose();
            }
        });

        c.insets = new Insets(0, 5, 10, 0);
        c.gridx = 0;
        c.gridy = 1;
        c.gridwidth = 1;
        c.ipadx = 200;

        //panelDialogo.add(table, c);
        panelDialogo.add(scroll, c);
        dialogoEditar.add(panelDialogo);
        dialogoEditar.setVisible(true);
    } catch (Exception e) {
        mensajesBusquedaClientesFactura.setText("La identificacion debe ser un numero");

    }

}

From source file:interfaces.InterfazPrincipal.java

private void BotonBuscarClienteSaldoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BotonBuscarClienteSaldoActionPerformed
    String nombreCliente = nombreClienteBusquedaSaldo.getText();
    //08-11-2014 listar clientes por nombre
    ControladorCliente controladorCliente = new ControladorCliente();
    ArrayList<Cliente> listaClientes = new ArrayList<>();

    if (nombreCliente.equals("")) {
        listaClientes = controladorCliente.obtenerClientes();
    } else {//from   ww w .j av  a  2s  .  c  o  m
        listaClientes = controladorCliente.obtenerClientes(nombreCliente, 0);
    }

    //08-11-2014 Crear dialogo de bsqueda
    final JDialog dialogoEditar = new JDialog(this);

    dialogoEditar.setTitle("Buscar clientes");
    dialogoEditar.setSize(300, 300);
    dialogoEditar.setResizable(false);

    JPanel panelDialogo = new JPanel();

    panelDialogo.setLayout(new GridBagLayout());

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

    JLabel ediitarTextoPrincipalDialogo = new JLabel("Buscar cliente");
    c.gridx = 0;
    c.gridy = 0;
    c.gridwidth = 2;
    c.insets = new Insets(10, 60, 10, 10);
    Font textoGrande = new Font("Arial", 1, 16);
    ediitarTextoPrincipalDialogo.setFont(textoGrande);
    panelDialogo.add(ediitarTextoPrincipalDialogo, c);

    c.gridx = 0;
    c.gridy = 1;
    c.gridwidth = 2;
    c.insets = new Insets(10, 10, 10, 10);
    final JTable tablaDialogo = new JTable();
    DefaultTableModel modeloTabla = new DefaultTableModel() {

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

    modeloTabla.addColumn("Identificacin");
    modeloTabla.addColumn("Nombre");

    //LLenar tabla
    for (int i = 0; i < listaClientes.size(); i++) {
        Object[] data = { "1", "2" };
        data[0] = listaClientes.get(i).getCliente_id();
        data[1] = listaClientes.get(i).getNombre();
        modeloTabla.addRow(data);
    }

    tablaDialogo.setModel(modeloTabla);
    tablaDialogo.getColumn("Identificacin").setMinWidth(110);
    tablaDialogo.getColumn("Nombre").setMinWidth(110);
    tablaDialogo.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    JScrollPane scroll = new JScrollPane(tablaDialogo);
    scroll.setPreferredSize(new Dimension(220, 150));

    panelDialogo.add(scroll, c);

    c.insets = new Insets(0, 0, 0, 10);
    c.gridx = 0;
    c.gridy = 2;
    c.gridwidth = 1;
    JButton botonGuardarClienteDialogo = new JButton("Elegir");
    panelDialogo.add(botonGuardarClienteDialogo, c);

    c.gridx = 1;
    c.gridy = 2;
    c.gridwidth = 1;
    JButton botonCerrarClienteDialogo = new JButton("Cancelar");
    panelDialogo.add(botonCerrarClienteDialogo, c);

    dialogoEditar.add(panelDialogo);
    dialogoEditar.setVisible(true);

    botonCerrarClienteDialogo.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            dialogoEditar.dispose();
        }
    });

    botonGuardarClienteDialogo.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            int row = tablaDialogo.getSelectedRow();
            if (row == -1) {
                JOptionPane.showMessageDialog(dialogoEditar, "Por favor seleccione una fila");

            } else {
                Object identificacionCliente = tablaDialogo.getValueAt(row, 0);
                mostrarIdentificacionCliente.setText(String.valueOf(identificacionCliente));
                String nombreClientePago = String.valueOf(tablaDialogo.getValueAt(row, 1));

                //Limitar a 15 caracteres
                if (nombreClientePago.length() >= 15) {
                    nombreClientePago = nombreClientePago.substring(0, 12);

                }
                textoPersonaSaldo.setText(nombreClientePago);

                DefaultTableModel modeloClientes = (DefaultTableModel) TablaDeSaldoClientes.getModel();
                for (int i = 0; i < modeloClientes.getRowCount(); i++) {
                    modeloClientes.removeRow(i);
                }

                modeloClientes.setRowCount(0);
                ControladorFlujoFactura controladorFlujoFactura = new ControladorFlujoFactura();

                //SELECT * FROM Flujo_Factura where factura_id in (select factura_id from Factura where cliente_id = 1130614506);
                ArrayList<String[]> flujosCliente = controladorFlujoFactura.getTodosFlujo_Factura(
                        " where factura_id in (select factura_id from Factura where cliente_id = "
                                + String.valueOf(identificacionCliente)
                                + " and estado=\"fiado\") order by factura_id");
                double pago = 0.0;

                for (int i = 0; i < flujosCliente.size(); i++) {
                    String[] datos = flujosCliente.get(i);

                    TablaDeSaldoClientes.setModel(modeloClientes);
                    NumberFormat formatter = new DecimalFormat("#0");

                    String valorMovimiento = String.valueOf(formatter.format(Double.parseDouble(datos[4])));
                    Object[] rowData = { datos[1], datos[2], datos[3], valorMovimiento };

                    if (datos[2].equals("deuda")) {
                        pago += Double.parseDouble(datos[4]);
                    } else {
                        pago -= Double.parseDouble(datos[4]);
                    }

                    modeloClientes.addRow(rowData);
                }

                TablaDeSaldoClientes.setModel(modeloClientes);
                NumberFormat formatter = new DecimalFormat("#0");
                textoTotalDebe.setText(String.valueOf(formatter.format(pago)));
                dialogoEditar.dispose();

                //Mostrar en table de clientes los datos
                botonRegistrarAbono.setEnabled(true);
            }

        }
    });
}

From source file:interfaces.InterfazPrincipal.java

private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed
    String nombreCliente = nombreClienteReporteCliente.getText();
    String identificacion = identificacionClienteCliente.getText();
    try {/* w  ww.  j  a v  a 2  s  . co m*/
        //08-11-2014 listar clientes por nombre
        ControladorCliente controladorCliente = new ControladorCliente();
        ArrayList<Cliente> listaClientes = new ArrayList<Cliente>();

        if (nombreCliente.equals("") && identificacion.equals("")) {
            listaClientes = controladorCliente.obtenerClientes();
        } else {
            int identificacionNumerico = 0;
            if (!identificacion.equals("")) {
                identificacionNumerico = Integer.parseInt(identificacion);
            }
            listaClientes = controladorCliente.obtenerClientes(nombreCliente, identificacionNumerico);
        }

        //08-11-2014 Crear dialogo de bsqueda
        final JDialog dialogoEditar = new JDialog(this);

        dialogoEditar.setTitle("Buscar clientes");
        dialogoEditar.setSize(300, 300);
        dialogoEditar.setResizable(false);

        JPanel panelDialogo = new JPanel();

        panelDialogo.setLayout(new GridBagLayout());

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

        JLabel ediitarTextoPrincipalDialogo = new JLabel("Buscar cliente");
        c.gridx = 0;
        c.gridy = 0;
        c.gridwidth = 2;
        c.insets = new Insets(10, 60, 10, 10);
        Font textoGrande = new Font("Arial", 1, 16);
        ediitarTextoPrincipalDialogo.setFont(textoGrande);
        panelDialogo.add(ediitarTextoPrincipalDialogo, c);

        c.gridx = 0;
        c.gridy = 1;
        c.gridwidth = 2;
        c.insets = new Insets(10, 10, 10, 10);
        final JTable tablaDialogo = new JTable();
        DefaultTableModel modeloTabla = new DefaultTableModel() {

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

        modeloTabla.addColumn("Identificacin");
        modeloTabla.addColumn("Nombre");

        //LLenar tabla
        for (int i = 0; i < listaClientes.size(); i++) {
            Object[] data = { "1", "2" };
            data[0] = listaClientes.get(i).getCliente_id();
            data[1] = listaClientes.get(i).getNombre();
            modeloTabla.addRow(data);
        }

        tablaDialogo.setModel(modeloTabla);
        tablaDialogo.getColumn("Identificacin").setMinWidth(110);
        tablaDialogo.getColumn("Nombre").setMinWidth(110);
        tablaDialogo.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        JScrollPane scroll = new JScrollPane(tablaDialogo);
        scroll.setPreferredSize(new Dimension(220, 150));

        panelDialogo.add(scroll, c);

        c.insets = new Insets(0, 0, 0, 10);
        c.gridx = 0;
        c.gridy = 2;
        c.gridwidth = 1;
        JButton botonGuardarClienteDialogo = new JButton("Elegir");
        panelDialogo.add(botonGuardarClienteDialogo, c);

        c.gridx = 1;
        c.gridy = 2;
        c.gridwidth = 1;
        JButton botonCerrarClienteDialogo = new JButton("Cancelar");
        panelDialogo.add(botonCerrarClienteDialogo, c);

        dialogoEditar.add(panelDialogo);
        dialogoEditar.setVisible(true);

        botonCerrarClienteDialogo.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                dialogoEditar.dispose();
            }
        });

        botonGuardarClienteDialogo.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                int row = tablaDialogo.getSelectedRow();
                if (row == -1) {
                    JOptionPane.showMessageDialog(dialogoEditar, "Por favor seleccione una fila");

                } else {
                    Object identificacionCliente = tablaDialogo.getValueAt(row, 0);
                    jTextFieldIdentificacionClienteReporte.setText(String.valueOf(identificacionCliente));
                    botonGenerarReporteCliente.setEnabled(true);
                    dialogoEditar.dispose();

                }

            }
        }); // TODO add your handling code here:     
    } catch (Exception e) {
        JOptionPane.showMessageDialog(this, "El valor de la identificacin de ser numrico");

    }

}

From source file:interfaces.InterfazPrincipal.java

private void jButton9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton9ActionPerformed
    // TODO add your handling code here:
    String nombre = jTextFieldNombreSaldoProveedores.getText();
    ControladorProveedores controladorProveedores = new ControladorProveedores();
    ArrayList<Proveedores> listaProveedores = controladorProveedores.obtenerProveedores("", nombre);

    final JDialog dialogoEditar = new JDialog(this);

    dialogoEditar.setTitle("Buscar proveedores");
    dialogoEditar.setSize(500, 300);// w w  w .  ja va2s  .c o  m
    dialogoEditar.setResizable(false);

    JPanel panelDialogo = new JPanel();

    panelDialogo.setLayout(new GridBagLayout());

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

    JLabel ediitarTextoPrincipalDialogo = new JLabel("Buscar Proveedores");
    c.gridx = 0;
    c.gridy = 0;
    c.gridwidth = 3;
    c.insets = new Insets(10, 60, 10, 10);
    Font textoGrande = new Font("Arial", 1, 16);
    ediitarTextoPrincipalDialogo.setFont(textoGrande);
    panelDialogo.add(ediitarTextoPrincipalDialogo, c);

    c.gridx = 0;
    c.gridy = 1;
    c.gridwidth = 3;
    c.insets = new Insets(10, 10, 10, 10);
    final JTable tablaDialogo = new JTable();
    DefaultTableModel modeloTabla = new DefaultTableModel() {

        @Override
        public boolean isCellEditable(int row, int column) {
            //all cells false
            return false;
        }
    };
    ;
    modeloTabla.addColumn("ID");
    modeloTabla.addColumn("Identificacin");
    modeloTabla.addColumn("Nombre");

    //LLenar tabla
    for (int i = 0; i < listaProveedores.size(); i++) {
        Object[] data = { "1", "2", "3" };
        data[0] = listaProveedores.get(i).getID();
        data[1] = listaProveedores.get(i).getIdentificacion();
        data[2] = listaProveedores.get(i).getNombre();
        System.out.println("Nombre!!" + data[2]);
        modeloTabla.addRow(data);
    }

    tablaDialogo.setModel(modeloTabla);
    tablaDialogo.getColumn("ID").setMinWidth(70);
    tablaDialogo.getColumn("Identificacin").setMinWidth(60);
    tablaDialogo.getColumn("Nombre").setMinWidth(150);
    tablaDialogo.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    JScrollPane scroll = new JScrollPane(tablaDialogo);
    scroll.setPreferredSize(new Dimension(220, 150));

    panelDialogo.add(scroll, c);

    c.insets = new Insets(0, 0, 0, 10);
    c.gridx = 0;
    c.gridy = 2;
    c.gridwidth = 1;
    JButton botonGuardarClienteDialogo = new JButton("Elegir");
    panelDialogo.add(botonGuardarClienteDialogo, c);

    c.gridx = 1;
    c.gridy = 2;
    c.gridwidth = 1;
    JButton botonCerrarClienteDialogo = new JButton("Cancelar");
    panelDialogo.add(botonCerrarClienteDialogo, c);

    dialogoEditar.add(panelDialogo);
    dialogoEditar.setVisible(true);

    botonCerrarClienteDialogo.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            dialogoEditar.dispose();
        }
    });

    botonGuardarClienteDialogo.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            int row = tablaDialogo.getSelectedRow();
            if (row == -1) {
                JOptionPane.showMessageDialog(dialogoEditar, "Por favor seleccione una fila");

            } else {
                Object identificacionCliente = tablaDialogo.getValueAt(row, 0);
                Object idCliente = tablaDialogo.getValueAt(row, 1);
                mostrarIDProveedor.setText(String.valueOf(identificacionCliente));
                String nombreClientePago = String.valueOf(tablaDialogo.getValueAt(row, 2));

                //Limitar a 15 caracteres
                if (nombreClientePago.length() >= 15) {
                    nombreClientePago = nombreClientePago.substring(0, 12);

                }
                textoNombreProveedor.setText(nombreClientePago);

                DefaultTableModel modeloClientes = (DefaultTableModel) TablaDeSaldoProveedor.getModel();
                for (int i = 0; i < modeloClientes.getRowCount(); i++) {
                    modeloClientes.removeRow(i);
                }

                modeloClientes.setRowCount(0);
                ControladorFlujoCompras controladorFlujoCompra = new ControladorFlujoCompras();

                //SELECT * FROM Flujo_Factura where factura_id in (select factura_id from Factura where cliente_id = 1130614506);
                ArrayList<Flujo_Compra> flujosProveedor = controladorFlujoCompra.obtenerFlujosCompras(
                        " where ID_CompraProveedor in (select ID_CompraProveedor from Compra_Proveedores where IDProveedor = "
                                + String.valueOf(identificacionCliente) + ") order by ID_CompraProveedor");
                double pago = 0.0;

                for (int i = 0; i < flujosProveedor.size(); i++) {
                    Flujo_Compra datos = flujosProveedor.get(i);
                    Object[] rowData = { datos.getID_CompraProveedor(), datos.getTipo_flujo(), datos.getFecha(),
                            datos.getMonto() };

                    if (datos.getTipo_flujo().equals("deuda")) {
                        pago += Double.parseDouble(datos.getMonto() + "");
                    } else {
                        pago -= Double.parseDouble(datos.getMonto() + "");
                    }

                    modeloClientes.addRow(rowData);
                }

                TablaDeSaldoProveedor.setModel(modeloClientes);
                deudaActualProveedor.setText(String.valueOf(pago));
                dialogoEditar.dispose();

                //Mostrar en table de clientes los datos
                botonRegistrarAbono.setEnabled(true);
            }

        }

    });

}

From source file:interfaces.InterfazPrincipal.java

private void botonAgregarProductoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonAgregarProductoActionPerformed
    String nombre = jTextField_Factura_Producto_Nombre.getText();
    String descripcion = jTextField_Factura_Producto_Descripcion.getText();
    ControladorProducto controladorPro = new ControladorProducto();
    String restriccion = "";

    boolean encounter = true;

    if (!nombre.equals("")) {
        if (encounter) {
            encounter = false;//from   w w  w . ja v a 2 s. c  o m
            restriccion = " where ";
        } else {
            restriccion += " OR ";
        }

        restriccion += " nombre like '%" + nombre + "%'";
    }

    if (!descripcion.equals("")) {
        if (encounter) {
            encounter = false;
            restriccion = " where ";
        } else {
            restriccion += " OR ";
        }

        restriccion += " descripcion like '%" + descripcion + "%'";
    }

    ArrayList<Productos> listaDeProductos = controladorPro.getProducto(restriccion);

    final JDialog dialogoEditar = new JDialog(this);
    dialogoEditar.setTitle("Buscar clientes");
    dialogoEditar.setSize(600, 310);
    dialogoEditar.setResizable(false);

    JPanel panelDialogo = new JPanel();

    panelDialogo.setLayout(new GridBagLayout());

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

    JLabel editarTextoPrincipalDialogo = new JLabel("Buscar Producto");
    c.gridx = 0;
    c.gridy = 0;
    c.gridwidth = 6;
    c.insets = new Insets(15, 200, 40, 0);
    c.ipadx = 100;
    Font textoGrande = new Font("Arial", 1, 18);
    editarTextoPrincipalDialogo.setFont(textoGrande);
    panelDialogo.add(editarTextoPrincipalDialogo, c);

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

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

    modeloTabla.addColumn("Numero");
    modeloTabla.addColumn("Identificacin");
    modeloTabla.addColumn("Nombre");
    modeloTabla.addColumn("Descripcion");
    modeloTabla.addColumn("Unidades Disponibles");
    modeloTabla.addColumn("Precio");

    //LLenar tabla
    for (int i = 0; i < listaDeProductos.size(); i++) {
        Object[] data = { "1", "2", "3", "4", "5", "6" };
        data[0] = (i + 1);
        data[1] = listaDeProductos.get(i).getProductoId();
        data[2] = listaDeProductos.get(i).getNombre();
        data[3] = listaDeProductos.get(i).getDescripcion();
        data[4] = listaDeProductos.get(i).getUnidadesDisponibles();
        data[5] = listaDeProductos.get(i).getPrecio();

        modeloTabla.addRow(data);
    }

    table.setModel(modeloTabla);
    table.getColumn("Numero").setMinWidth(50);
    table.getColumn("Identificacin").setMinWidth(50);
    table.getColumn("Nombre").setMinWidth(110);
    table.getColumn("Descripcion").setMinWidth(110);
    table.getColumn("Unidades Disponibles").setMinWidth(40);
    table.getColumn("Precio").setMinWidth(110);

    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    JScrollPane scroll = new JScrollPane(table);
    scroll.setPreferredSize(new Dimension(320, 150));

    //final JTable table = new JTable(row, col);       
    table.addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent e) {
            //jTextField_Factura_Cliente_Id.setText(table.getValueAt(table.getSelectedRow(), 1).toString());
            //System.out.println(table.getValueAt(table.getSelectedRow(), 3).toString());
            DefaultTableModel modelo = (DefaultTableModel) TablaDeFacturaProducto.getModel();

            Object[] fila = new Object[7];

            fila[0] = table.getValueAt(table.getSelectedRow(), 0).toString();
            fila[1] = table.getValueAt(table.getSelectedRow(), 1).toString();
            fila[2] = table.getValueAt(table.getSelectedRow(), 2).toString();
            fila[3] = table.getValueAt(table.getSelectedRow(), 3).toString();
            //fila[4] = table.getValueAt(table.getSelectedRow(), 4).toString();
            fila[4] = (String) JOptionPane.showInputDialog("Ingrese el nmero de unidades que va a vender");
            fila[5] = table.getValueAt(table.getSelectedRow(), 5).toString();

            Double valorProducto = Double.parseDouble((String) fila[5]);
            String valorActualProducto = String.valueOf(Double.parseDouble(valorActualFactura.getText())
                    + Double.parseDouble((String) fila[4]) * valorProducto);
            valorActualFactura.setText(valorActualProducto);
            fila[6] = Double.parseDouble((String) fila[4]) * valorProducto;
            modelo.addRow(fila);
            //modelo.getColumnName(4).
            /*TablaDeFacturaProducto.setModel(modelo);
             TablaDeFacturaProducto.getColumnClass(4). ;*/
            dialogoEditar.dispose();
        }
    });

    c.insets = new Insets(0, 5, 10, 0);
    c.gridx = 0;
    c.gridy = 1;
    c.gridwidth = 1;
    c.ipadx = 200;

    panelDialogo.add(scroll, c);

    //panelDialogo.add(table, c);
    dialogoEditar.add(panelDialogo);
    dialogoEditar.setVisible(true);

}

From source file:fi.hoski.remote.ui.Admin.java

private void editReservations(final EventType eventType) {
    final Event event = chooseEvent(eventType, "CHOOSE");
    if (event != null) {
        final String eventTitle = TextUtil.getText(event.getEventType().name()) + " "
                + event.get(Event.EventDate);
        safeTitle = frame.getTitle();//from w ww.j  ava  2  s .co m
        frame.setTitle(eventTitle);
        reservationList = dss.getReservations(event);
        selectedReservations = new ArrayList<Reservation>();
        unSelectedReservations = new ArrayList<Reservation>();
        if (Event.isInspection(eventType)) {
            for (Reservation reservation : reservationList) {
                Boolean inspected = (Boolean) reservation.get(Reservation.INSPECTED);
                if (inspected != null && inspected) {
                    selectedReservations.add(reservation);
                } else {
                    unSelectedReservations.add(reservation);
                }
            }
        } else {
            for (Reservation reservation : reservationList) {
                Long order = (Long) reservation.get(Reservation.ORDER);
                if (order != null && order != 0) {
                    selectedReservations.add(reservation);
                } else {
                    unSelectedReservations.add(reservation);
                }
            }
        }
        DataObjectModel baseModel = Reservation.getModel(eventType);
        DataObjectModel unorderedModel = null;
        DataObjectModel orderedModel = null;
        switch (eventType) {
        case LAUNCH:
        case LIFT:
        case HULL_INSPECTION:
            unorderedModel = baseModel.hide(Reservation.BOAT, Reservation.INSPECTED, Reservation.CREATOR);
            orderedModel = baseModel.hide(Reservation.BOAT, Reservation.INSPECTED, Reservation.CREATOR);
            break;
        case INSPECTION:
            unorderedModel = baseModel.hide(Reservation.BOAT, Reservation.INSPECTED, Reservation.CREATOR,
                    Reservation.EMAIL, Reservation.MOBILEPHONE, Reservation.DOCK, Reservation.DOCKNUMBER,
                    Reservation.INSPECTION_GASS, Reservation.INSPECTOR);
            orderedModel = baseModel.hide(Reservation.BOAT, Reservation.INSPECTED, Reservation.CREATOR,
                    Reservation.EMAIL, Reservation.MOBILEPHONE, Reservation.DOCK, Reservation.DOCKNUMBER,
                    Reservation.NOTES);
            break;
        }

        final DataObjectListTableModel<Reservation> unorderedTableModel = new DataObjectListTableModel<Reservation>(
                unorderedModel, unSelectedReservations);
        final JTable unorderedtable = new FitTable(unorderedTableModel);
        TableSelectionHandler tsh1 = new TableSelectionHandler(unorderedtable);
        unorderedtable.setDefaultRenderer(String.class, new StringTableCellRenderer());
        unorderedtable.setDefaultRenderer(Text.class, new TextTableCellRenderer());

        unorderedtable.addKeyListener(unorderedTableModel.getRemover(dss));
        unorderedtable.setDragEnabled(true);
        unorderedtable.setDropMode(DropMode.INSERT_ROWS);
        TransferHandler unorderedTransferHandler = new DataObjectTransferHandler<Reservation>(
                unorderedTableModel);
        unorderedtable.setTransferHandler(unorderedTransferHandler);

        final DataObjectListTableModel<Reservation> orderedTableModel = new DataObjectListTableModel<Reservation>(
                orderedModel, selectedReservations);
        orderedTableModel.setEditable(Reservation.INSPECTION_CLASS, Reservation.INSPECTION_GASS,
                Reservation.BASICINSPECTION, Reservation.INSPECTOR);
        final JTable orderedtable = new FitTable(orderedTableModel);
        TableSelectionHandler tsh2 = new TableSelectionHandler(orderedtable);
        orderedtable.setDefaultRenderer(String.class, new StringTableCellRenderer());
        orderedtable.setDefaultRenderer(Text.class, new TextTableCellRenderer());

        orderedtable.addKeyListener(orderedTableModel.getRemover(dss));
        orderedtable.setDragEnabled(true);
        orderedtable.setDropMode(DropMode.INSERT_ROWS);
        TransferHandler orderedTransferHandler = new DataObjectTransferHandler<Reservation>(orderedTableModel);
        orderedtable.setTransferHandler(orderedTransferHandler);
        if (Event.isInspection(eventType)) {
            unorderedtable.setAutoCreateRowSorter(true);
            orderedtable.setAutoCreateRowSorter(true);
        }
        leftPane = new JScrollPane();
        leftPane.setViewport(new InfoViewport(TextUtil.getText(eventType.name() + "-leftPane")));
        leftPane.setViewportView(unorderedtable);
        leftPane.setTransferHandler(unorderedTransferHandler);

        rightPane = new JScrollPane();
        rightPane.setViewport(new InfoViewport(TextUtil.getText(eventType.name() + "-rightPane")));
        rightPane.setViewportView(orderedtable);
        rightPane.setTransferHandler(orderedTransferHandler);

        splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPane, rightPane);
        splitPane.setDividerLocation(0.5);
        menuReservation.setEnabled(false);
        safeContainer = frame.getContentPane();
        JPanel contentPane = new JPanel(new BorderLayout());
        contentPane.add(splitPane, BorderLayout.CENTER);

        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new FlowLayout());
        contentPane.add(buttonPanel, BorderLayout.SOUTH);

        JButton saveButton = new JButton();
        TextUtil.populate(saveButton, "SAVE");
        saveButton.setEnabled(!Event.isInspection(eventType));
        ActionListener saveAction = new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                saveReservations();
            }
        };
        saveButton.addActionListener(saveAction);
        buttonPanel.add(saveButton);

        switch (eventType) {
        case INSPECTION: {
            if (privileged) {
                JButton inspectButton = new JButton();
                TextUtil.populate(inspectButton, "SET INSPECTED");
                ActionListener inspectAction = new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        TableCellEditor cellEditor = orderedtable.getCellEditor();
                        if (cellEditor != null) {
                            cellEditor.stopCellEditing();
                        }
                        try {
                            setAsInspected();
                        } catch (SQLException | ClassNotFoundException ex) {
                            ex.printStackTrace();
                            JOptionPane.showMessageDialog(null, ex.getMessage());
                        }
                    }
                };
                inspectButton.addActionListener(inspectAction);
                buttonPanel.add(inspectButton);
            }

            JButton addBoat = new JButton();
            TextUtil.populate(addBoat, "ADD BOAT");
            ActionListener addBoatAction = new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    Reservation reservation = reservate(eventType, event);
                    if (reservation != null) {
                        reservationList.add(reservation);
                        unSelectedReservations.add(reservation);
                        unorderedTableModel.fireTableDataChanged();
                    }
                }
            };
            addBoat.addActionListener(addBoatAction);
            buttonPanel.add(addBoat);

            JButton printTypeButton = new JButton();
            TextUtil.populate(printTypeButton, "PRINT");
            ActionListener printTypeAction = new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    try {
                        printNameBoatTypeOrder(eventTitle);
                    } catch (PrinterException ex) {
                        ex.printStackTrace();
                        JOptionPane.showMessageDialog(null, ex.getMessage());
                    }
                }
            };
            printTypeButton.addActionListener(printTypeAction);
            buttonPanel.add(printTypeButton);

            JButton printDockButton = new JButton();
            TextUtil.populate(printDockButton, "PRINT DOCK ORDER");
            ActionListener printDockAction = new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    try {
                        printDockOrder(eventTitle);
                    } catch (PrinterException ex) {
                        ex.printStackTrace();
                        JOptionPane.showMessageDialog(null, ex.getMessage());
                    }
                }
            };
            printDockButton.addActionListener(printDockAction);
            buttonPanel.add(printDockButton);

        }
            break;
        case HULL_INSPECTION: {
            JButton print = new JButton();
            TextUtil.populate(print, "PRINT");
            ActionListener printAction = new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    try {
                        printAlphaOrder(eventTitle);
                    } catch (PrinterException ex) {
                        ex.printStackTrace();
                        JOptionPane.showMessageDialog(null, ex.getMessage());
                    }
                }
            };
            print.addActionListener(printAction);
            buttonPanel.add(print);

        }
            break;
        case LAUNCH:
        case LIFT: {
            JButton addBoat = new JButton();
            TextUtil.populate(addBoat, "ADD BOAT");
            ActionListener addBoatAction = new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    Reservation reservation = reservate(eventType, event);
                    if (reservation != null) {
                        reservationList.add(reservation);
                        unSelectedReservations.add(reservation);
                        unorderedTableModel.fireTableDataChanged();
                    }
                }
            };
            addBoat.addActionListener(addBoatAction);
            buttonPanel.add(addBoat);

            JButton printBrief = new JButton();
            TextUtil.populate(printBrief, "BRIEF PRINT");
            ActionListener printBriefAction = new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    try {
                        printOrderBrief(eventTitle);
                    } catch (PrinterException ex) {
                        ex.printStackTrace();
                        JOptionPane.showMessageDialog(null, ex.getMessage());
                    }
                }
            };
            printBrief.addActionListener(printBriefAction);
            buttonPanel.add(printBrief);

            JButton print = new JButton();
            TextUtil.populate(print, "PRINT");
            ActionListener printAction = new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    try {
                        if (eventType == EventType.LAUNCH) {
                            printLaunchOrder(eventTitle);
                        } else {
                            printLiftOrder(eventTitle);
                        }
                    } catch (PrinterException ex) {
                        ex.printStackTrace();
                        JOptionPane.showMessageDialog(null, ex.getMessage());
                    }
                }
            };
            print.addActionListener(printAction);
            buttonPanel.add(print);
        }
            break;
        }

        JButton cancelButton = new JButton();
        TextUtil.populate(cancelButton, "CANCEL");
        ActionListener cancelAction = new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                cancel();
            }
        };
        cancelButton.addActionListener(cancelAction);
        buttonPanel.add(cancelButton);

        frame.setContentPane(contentPane);
        frame.pack();
        frame.setVisible(true);
        KeyListener keyListener = new KeyAdapter() {

            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == 10) {
                    int selectedRow = unorderedtable.getSelectedRow();
                    if (selectedRow != -1) {
                        RowSorter<? extends TableModel> rowSorter = unorderedtable.getRowSorter();
                        if (rowSorter != null) {
                            selectedRow = rowSorter.convertRowIndexToModel(selectedRow);
                        }
                        Reservation reservation = unorderedTableModel.getObject(selectedRow);
                        orderedTableModel.add(reservation);
                        unorderedTableModel.remove(reservation);
                        e.consume();
                        unorderedtable.changeSelection(selectedRow, 0, false, false);
                    }
                }
            }
        };
        unorderedtable.addKeyListener(keyListener);
        unorderedtable.requestFocusInWindow();
    }
}

From source file:org.apache.cayenne.modeler.editor.ObjEntityRelationshipPanel.java

protected void rebuildTable(ObjEntity entity) {
    final ObjRelationshipTableModel model = new ObjRelationshipTableModel(entity, mediator, this);

    model.addTableModelListener(new TableModelListener() {

        public void tableChanged(TableModelEvent e) {
            if (table.getSelectedRow() >= 0) {
                ObjRelationship rel = model.getRelationship(table.getSelectedRow());
                enabledResolve = rel.getSourceEntity().getDbEntity() != null;
                resolveMenu.setEnabled(enabledResolve);
            }/*from   w  w  w.ja v  a 2  s . c  om*/
        }
    });

    table.setModel(model);
    table.setRowHeight(25);
    table.setRowMargin(3);

    TableColumn col = table.getColumnModel().getColumn(ObjRelationshipTableModel.REL_TARGET_PATH);
    col.setCellEditor(new DbRelationshipPathComboBoxEditor());
    col.setCellRenderer(new DefaultTableCellRenderer() {
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                boolean hasFocus, int row, int column) {
            super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
            setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0));
            setToolTipText(
                    "To choose relationship press enter two times.To choose next relationship press dot.");
            return this;
        }
    });

    col = table.getColumnModel().getColumn(ObjRelationshipTableModel.REL_DELETE_RULE);
    JComboBox deleteRulesCombo = Application.getWidgetFactory().createComboBox(DELETE_RULES, false);
    deleteRulesCombo.setFocusable(false);
    deleteRulesCombo.setEditable(true);
    ((JComponent) deleteRulesCombo.getEditor().getEditorComponent()).setBorder(null);
    deleteRulesCombo.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0));
    deleteRulesCombo.setSelectedIndex(0); // Default to the first value
    col.setCellEditor(Application.getWidgetFactory().createCellEditor(deleteRulesCombo));

    tablePreferences.bind(table, null, null, null, ObjRelationshipTableModel.REL_NAME, true);
}

From source file:org.dc.file.search.ui.DashboardForm.java

public ButtonPanel(JTable jTable) {
    this.jTable = jTable;
    setLayout(new GridLayout());
    setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

    button.addActionListener(e -> {//  w  ww.ja va  2s . c  o m
        int row = jTable.getSelectedRow();
        if (row == -1) {
            JOptionPane.showMessageDialog(this, "Please select a comment first.", "Information",
                    JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        String commentId = jTable.getValueAt(jTable.getSelectedRow(), 0).toString();
        String commentString = JOptionPane.showInputDialog(null, "Add reply for " + commentId,
                "Add A New Reply", JOptionPane.QUESTION_MESSAGE);
        if (commentString != null && !commentString.isEmpty()) {
            String username = Store.getInstance().getLocalPeer().getUsername();
            DFile commentedFile = resultFiles.get(selectedFile);
            List<Comment> comments = commentedFile.getComments();
            Comment selectedComment = null;
            for (Comment c : comments) {
                if (c.getCommentId().equals(commentId)) {
                    selectedComment = c;
                    break;
                }
            }

            if (selectedComment != null) {
                Comment replyComment = new Comment();
                replyComment.setCommentId(RandomStringUtils.randomAlphanumeric(8));
                replyComment.setFileName(selectedFile);
                replyComment.setParentId(commentId);
                replyComment.setUserName(username);
                replyComment.setText(commentString);

                selectedComment.getReplies().add(replyComment);
                Store.getInstance().addComment(replyComment);
                final String commentJSON = new Gson().toJson(replyComment);
                Store.getInstance().getPeerList().forEach(stringPeerEntry -> {
                    String peerIP = stringPeerEntry.getValue().getIp();
                    int peerPort = stringPeerEntry.getValue().getPort();
                    Peer localPeer = Store.getInstance().getLocalPeer();
                    MessageUtils.sendUDPMessage(peerIP, peerPort, MessageType.COMMENT + " " + localPeer.getIp()
                            + " " + localPeer.getPort() + " " + commentJSON);
                });
            }
        }
    });
    add(button);
}