Select a row of a JTable and pass data to jTextFields - JAVA

0

I have a class called " Compra.java " ( JFrame ) where there is a JTable with NO purchased vehicles available for sale, if I select a row (a vehicle) from that table and pulse the JButton " button_buy "you should send me to a JDialog form called" Comprar_vehiculo.java "where that data in the table is automatically loaded in jTextField of the table.

How do I pass the data from the columns in the table to the jTextField fields?

Descriptive image of problem 1: link

Descriptive image of problem 2: link

Code attempted:

private void button_comprarActionPerformed(java.awt.event.ActionEvent evt) {                                               
        int filaseleccionada;
        try{
            //Guardamos en un entero la fila seleccionada.
            filaseleccionada = table_comprados.getSelectedRow();
            if (filaseleccionada == -1){
                JOptionPane.showMessageDialog(null, "No ha seleccionado ninguna fila.");
            } else {
                Comprar_vehiculo cv = new Comprar_vehiculo(null, rootPaneCheckingEnabled);
                cv.setVisible(true);

                //String ayuda = tabla.getValueAt(filaseleccionada, num_columna).toString()); 
                String bastidor = (String)table_comprados.getValueAt(filaseleccionada, 0);
                String color = (String)table_comprados.getValueAt(filaseleccionada, 1);
                String matricula = (String)table_comprados.getValueAt(filaseleccionada, 2);
                String marca = (String)table_comprados.getValueAt(filaseleccionada, 3);
//                textfield_bastidor.setText(bastidor);
//                textfield_color.setText(color);
//                textfield_marca.setText(email);
//                textfield_modelo.setText(matricula);
//                textfield_matricula.setText(marca);
            }
        }catch (HeadlessException ex){
            JOptionPane.showMessageDialog(null, "Error: "+ex+"\nInténtelo nuevamente", " .::Error En la Operacion::." ,JOptionPane.ERROR_MESSAGE);
        }        
    } 
    
asked by omaza1990 13.01.2017 в 09:38
source

2 answers

2

A small example of how this kind of functionality could be applied:

  • A model (similar)
  • MainView with an addListener (ActionListener al) and getters for the components that will be passed reference between views
  • Secondary View (my example is to edit a value ..)
  • A listener to separate it from the view and to better communicate the components.
  • A controller that communicates litener with view
  • If it is set, the controller is responsible for making the communication (references) between listeners and views.

    The listeners are responsible for using the view / model to perform the tasks received (through events).

    Everything is a delegation of tasks trying to separate tasks with different purposes.

    If you run the MainController you can see everything in action ...

    Controller and Main

    import javax.swing.SwingUtilities;
    
    import listeners.EditButtonListener;
    import m.Vehiculo;
    import v.TableFrame;
    
    public class MainController {
    
        public MainController(TableFrame v) {
    
            EditButtonListener ebl = new EditButtonListener(v);
    
            v.addListeners(ebl);
    
            v.addVehicle(new Vehiculo("911 carrera", "Porsche"));
            v.addVehicle(new Vehiculo("Diablo", "Lamborguini"));
    
        }
    
        public static void main(String[] args) {
    
            SwingUtilities.invokeLater(new Runnable() {
    
                @Override
                public void run() {
    
                    TableFrame frame = new TableFrame();
    
                    new MainController(frame);
                }
            });
        }
    }
    

    Secondary View

    import java.awt.FlowLayout;
    import java.awt.Point;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JTextField;
    
    import m.Vehiculo;
    
    public class VehicleEditPopUp extends JFrame {
    
        private static final long serialVersionUID = 1L;
    
        private Vehiculo vehicle;
        private TableFrame view;
    
        private JTextField inMarca;
    
        private JTextField inModelo;
    
        private JButton btnOk;
    
        private static final int COL_SIZE = 25;
    
        public VehicleEditPopUp(Vehiculo vehicl, TableFrame v, int editRow) {
    
            vehicle = vehicl;
            view = v;
    
            setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            setLayout(new FlowLayout(FlowLayout.CENTER, 0, 0));
    
            Point location = view.getLocation();
    
            setBounds((int) location.getX(), (int) location.getY(), 300, 600);
    
            inMarca = new JTextField(vehicle.getMarca(), COL_SIZE);
            inModelo = new JTextField(vehicle.getModelo(), COL_SIZE);
    
            btnOk = new JButton("Ok");
            // tambien hubiese sido posible crear un Listener aparte..
            // diferentes formas de hacer  las cosas.. 
            // cuando ya hay mucho código puede que sea mejor un Listener separado
            btnOk.addActionListener(new ActionListener() {
    
                @Override
                public void actionPerformed(ActionEvent e) {
    
                    String marca = inMarca.getText();
                    String modelo = inModelo.getText();
    
                    view.editVehicle(new Vehiculo(marca, modelo), editRow);
    
                    closePopUp();
                }
            });
    
            add(new JLabel("Marca"));
            add(inMarca);
            add(new JLabel("Modelo"));
            add(inModelo);
            add(btnOk);
    
            setVisible(true);
        }
    
        public void closePopUp() {
            this.dispose();
        }
    }
    

    Listener That helps VistaPrincipal

    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    import javax.swing.JButton;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableModel;
    
    import m.Vehiculo;
    import v.TableFrame;
    import v.VehicleEditPopUp;
    
    public class EditButtonListener implements ActionListener {
    
        private TableFrame view;
        private JButton btn;
        private DefaultTableModel model;
        private JTable table;
    
        public EditButtonListener(TableFrame v) {
            view = v;
    
            btn = view.getBtn();
    
            model = view.gettModel();
    
            table = view.getTable();
    
        }
    
        @Override
        public void actionPerformed(ActionEvent e) {
    
            if (e.getSource() == btn) {
    
                int row = table.getSelectedRow();
    
                if (row != -1) {
    
                    String marca = (String) table.getValueAt(row, 0);
                    String modelo = (String) table.getValueAt(row, 1);
    
                    Vehiculo selectedVehicle = new Vehiculo(marca, modelo);
    
                    new VehicleEditPopUp(selectedVehicle, view, row);
    
                } else {
    
                    Vehiculo emptyV = new Vehiculo();
                    view.addVehicle(emptyV);
                    new VehicleEditPopUp(emptyV, view, model.getRowCount() + 1);
    
                }
    
            }
        }
    
    }
    

    VistaPrincipal

    import java.awt.BorderLayout;
    import java.awt.event.ActionListener;
    
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableModel;
    
    import m.Vehiculo;
    
    public class TableFrame extends JFrame {
    
        private static final long serialVersionUID = 1L;
    
        private DefaultTableModel tModel;
    
        private JTable table;
    
        private JButton btn;
    
        public TableFrame() {
    
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setBounds(50, 50, 700, 600);
            setLayout(new BorderLayout(5, 5));
    
            String[] cols = { "Modelo", "Marca" };
    
            tModel = new DefaultTableModel();
            tModel.setColumnIdentifiers(cols);
            table = new JTable(tModel);
    
            btn = new JButton("Edit");
    
            add(new JScrollPane(table), BorderLayout.CENTER);
            add(btn, BorderLayout.SOUTH);
    
            setVisible(true);
        }
    
        public void addVehicle(Vehiculo v) {
    
            String[] data = { v.getMarca(), v.getModelo() };
            tModel.addRow(data);
            tModel.fireTableDataChanged();
        }
    
        public void editVehicle(Vehiculo v, int row) {
    
            String[] data = { v.getMarca(), v.getModelo() };
    
            for (int col = 0; col <= data.length - 1; col++) {
    
                tModel.setValueAt(data[col], row, col);
            }
    
            tModel.fireTableDataChanged();
        }
    
        public void addListeners(ActionListener al) {
            btn.addActionListener(al);
        }
    
        public DefaultTableModel gettModel() {
            return tModel;
        }
    
        public JTable getTable() {
            return table;
        }
    
        public JButton getBtn() {
            return btn;
        }
    
    }
    

    Model

    public class Vehiculo {
    
        private String modelo;
        private String marca;
        // setters & getters
        // constructor vacío & constructor con argumentos
    }
    
        
    answered by 14.01.2017 / 00:27
    source
    0

    A faster solution to your code is instead of writing

    (String)table_comprados.getValueAt(filaseleccionada, 0);
    

    write it as follows

    table_comprados.getValueAt(filaseleccionada, 0).toString();
    

    This is the way to convert an object to String.

        
    answered by 31.08.2017 в 18:25