1

Let me break my question in 2 parts.

  1. How to retrieve value from JTextfiled in JTable?
  2. After all the data how to store in database in one go?

Name and Age should be retrive from JTextfield on jbutton1 action and by clicking jbutton2 all the data of Jtable should be stored in SQL DB.

Below is my code:

package tablefilterdemo;


public class Tableinputhroughtextbox extends javax.swing.JFrame {

    public Tableinputhroughtextbox() {
        initComponents();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jtfname = new javax.swing.JTextField();
        jtfage = new javax.swing.JTextField();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null},
                {null, null},
                {null, null},
                {null, null}
            },
            new String [] {
                "Name", "Age"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        jButton1.setText("Submit for Table");

        jButton2.setText("Submit for SQL");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(29, 29, 29)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(53, 53, 53)
                        .addComponent(jtfname, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(46, 46, 46)
                        .addComponent(jtfage, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton1)
                        .addGap(18, 18, 18)
                        .addComponent(jButton2)))
                .addContainerGap(82, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(92, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jtfname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jtfage, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton2))
                .addGap(47, 47, 47)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 322, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(19, 19, 19))
        );

        pack();
    }// </editor-fold>                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Tableinputhroughtextbox.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Tableinputhroughtextbox.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Tableinputhroughtextbox.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Tableinputhroughtextbox.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Tableinputhroughtextbox().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jtfage;
    private javax.swing.JTextField jtfname;
    // End of variables declaration                   
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
user3172930
  • 175
  • 1
  • 2
  • 10

2 Answers2

4

1) How to retrive value from textfiled in JTable?

I assume you mean JTextField? Please be careful with your spelling since programming is an exercise in precision, and so you can't afford to be sloppy in your coding or your questions.

You get text just as the tutorials tell you, via the getText() method. Please have a look here.

2) After all the data how to store in database in one go?

Please clarify your question. If you're looking how to use databases with Java, look here. For how to use JTables and table models, please look here. I suggest that you separate out your database code from your Swing code, to help ease your debugging and coding.


Edit 1
Regarding using a JTable with a database, reams of answers have been posted on this question, and you would do well to search this site for these answers. It's not a trivial thing and will require a bit of study on your part. For example, please have a look at these links:


Edit 2
You ask in comment:

OK Let's stick one question.in above code I have create 2 JTexfield and and Button.Now here I want those retrieved data how can I show in Jtable?

If you want the data from the two JTextFields placed in a row of the JTable, consider doing the following:

  • In your button's ActionListener, first extract the text from the text from the JTextFields.
  • Next you will need to create a row for your JTable which means adding a row to the JTable's model. How this is done will depend entirely on how the TableModel is set up.
  • If you are using a DefaultTableModel object, then you'll want to create a Vector<String> or String array, place your two Strings into the Vector or array, and then call addRow(rowData) on your DefaultTableModel variable. This assumes that the vector or array is named rowData.
  • If you're using a custom TableModel based off of the AbstractTableModel, then you'll need to write your own addRow(...) method, and you will likely pass in an object of a custom class that holds your two pieces of data. If you go this route, make sure that your addRow(...) method calls the correct fireTableXXX(...) method, here it will be fireTableRowsInserted(int firstRow, int lastRow).

But most important, please be sure to read the JTable tutorial that I've linked to above, else my answers will not make sense to you.


Edit 3
For example, using a DefaultTableModel:

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.Vector;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;

@SuppressWarnings("serial")
public class MyTableEg extends JPanel {
   private static final String[] COLUMNS = {"Column A", "Column B"};
   private DefaultTableModel model = new DefaultTableModel(COLUMNS, 0);
   private JTable table = new JTable(model);
   private JTextField fieldA = new JTextField(10);
   private JTextField fieldB = new JTextField(10);
   private JButton button = new JButton(new ButtonAction("Add Data", KeyEvent.VK_A));

   public MyTableEg() {
      JPanel topPanel = new JPanel();
      topPanel.add(fieldA);
      topPanel.add(fieldB);
      topPanel.add(button);

      setLayout(new BorderLayout());
      add(topPanel, BorderLayout.NORTH);
      add(new JScrollPane(table), BorderLayout.CENTER);
   }

   private class ButtonAction extends AbstractAction {
      public ButtonAction(String name, int mnemonic) {
         super(name);
         putValue(MNEMONIC_KEY, mnemonic);
      }

      @Override
      public void actionPerformed(ActionEvent evt) {

         // ***** here's the important bit of code

         Vector<String> rowData = new Vector<String>();  // create a row Vector
         rowData.add(fieldA.getText());    // fill it with data from JTextFields
         rowData.add(fieldB.getText());
         model.addRow(rowData);            // and add to table model
      }
   }

   private static void createAndShowGui() {
      JFrame frame = new JFrame("MyTableEg");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(new MyTableEg());
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}
Community
  • 1
  • 1
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • I know .getText method of JTextfiled but here I want something like first to store in Array and those ArrayBased data we can see in JTable and regarding 2nd question I'm looking after insertion of all data those Array data will store in DB – user3172930 Jan 18 '14 at 14:40
  • 1
    @user3172930: you sound to be doing too much all at once. Try to solve each problem one at a time, and then come back with specific questions if you get stuck at a specific step. Also regarding using a JTable with a database, reams of answers have been posted on this question, and you would do well to search this site for these answers. It's not a trivial thing and will require a bit of study on your part. – Hovercraft Full Of Eels Jan 18 '14 at 14:43
  • OK Let's stick one question.in above code I have create 2 JTexfield and and Button.Now here I want those retrieved data how can I show in Jtable? – user3172930 Jan 18 '14 at 14:50
  • Thanks :D :D StackOverflow Team – user3172930 Jan 18 '14 at 16:36
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/45547/discussion-between-user3172930-and-hovercraft-full-of-eels) – user3172930 Jan 18 '14 at 16:42
0
//I guess you already got value into your JTextField
//Here I'm getting only two column into my JTable, you can take as many as you need

  jbutton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
             //TODO Auto-generated method stub

            DefaultTableModel model=(DefaultTableModel) table.getModel();

            try 
            {
                String s1,s2;
                s1=tfield1.getText();
                s2=tfield2.getText();
                model.addRow(new Object[] {s1,s2});

            }
            catch(Exception ae){ 
                ae.printStackTrace();

                }
        }
    });

It might help :)

imjhapali
  • 1
  • 2