Fill table with data entered in Jtextfield, separated by comma

Asked

Viewed 468 times

1

I have the code under a JTextField, where you wanted to type numbers separated by comma, and that by clicking on JButton, data were added in a table column.

public class Dados extends javax.swing.JPanel {

    public Dados() {
        initComponents();
    }

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

        jLabel1 = new javax.swing.JLabel();
        vNomes = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();

        jLabel1.setText("Digite os valores separados por virgula");

        jButton1.setText("Formar tabela");

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "classes", "Xi", "Fi", "Fac"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(33, 33, 33)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1)
                    .addComponent(vNomes, javax.swing.GroupLayout.PREFERRED_SIZE, 343, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(88, 88, 88)
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 119, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(214, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(31, 31, 31)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(vNomes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jButton1)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(412, Short.MAX_VALUE))
        );
    }// </editor-fold>                        


    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField vNomes;
    // End of variables declaration                   
}
  • Present a [mcve] so that it is possible to test the code and simulate the problem.

  • There is nothing implemented there about doubt, what you have tried to do?

  • I don’t know how to do anything, I just know the logic that would be to type numbers to fill the columns of the table , for example column Xi, making the first one then I will do the next.

  • Your doubt in this way is too wide. I suggest a read on Jtable, learn a little to handle and try something, and when painting a specific question, ask again.

  • Unless you want to, actually, make a text typed in a textfield to be inserted in a column, but your question does not specify which column and whether the addition will be fixed in that column.

  • that’s right, typed text, after clicking the button, fill in the column, can be qq one, and can be fixed

  • You need to explain better how this addition should be made, otherwise it becomes difficult to elaborate something.

  • ok, la, I need to fill a table with some numbers that will be typed, these numbers must fill a column in the table, example column Xi, when the user type, 1,2,3,4,5... click the button add, each value fills a row of the column, got it?

  • Is each column value separated by comma? What if it has more comma values than columns?

  • no, each value will be for a row.. of the same column would be:

  • See the answer below.

Show 6 more comments

1 answer

0


You can pick up the text from JTextField and use the method split() to separate the values separated by comma to then add to the table. As you are using DefaultTableMoldel, you can use the method addRow() to add lines.

To avoid additions when the field has nothing, I used the method trim() to remove empty spaces in String captured from the field, and the conditional to verify that string is not empty.

I couldn’t reproduce your code, it looks like it was generated by netbeans, but see working in the example I drew up below:

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.JTextField;
import javax.swing.JButton;

public class Dados2 extends JFrame {

    private JPanel contentPane;
    private JTextField textField;

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> new Dados2().setVisible(true));
    }

    public Dados2() {

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setPreferredSize(new Dimension(450, 300));
        contentPane = new JPanel(new BorderLayout());
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);

        JPanel panelField = new JPanel();
        contentPane.add(panelField, BorderLayout.NORTH);

        textField = new JTextField();
        panelField.add(textField);
        textField.setColumns(20);

        String[] columnNames = new String[] { "classes", "Xi", "Fi", "Fac" };

        DefaultTableModel model = new DefaultTableModel(columnNames, 0);
        JTable table = new JTable(model);
        JScrollPane scroll = new JScrollPane(table);

        contentPane.add(scroll, BorderLayout.CENTER);

        JPanel panelBtn = new JPanel();
        contentPane.add(panelBtn, BorderLayout.SOUTH);

        JButton jbutton = new JButton("Adicionar");
        panelBtn.add(jbutton);

        jbutton.addActionListener(e -> {

            String text = textField.getText();

            if (text.length() > 0 && text.contains(",")) {

                String[] values = text.split(",");

                for (int i = 0; i < values.length; i++) {
                    model.addRow(new Object[] { null, values[i], null, null });
                }
            }
        });
        pack();
    }
}

Working:

inserir a descrição da imagem aqui

It is worth noting that, in addition to the empty string, the conditional also checks for commas in the string, which causes plain text not to be added to a single line. If you want to change this behavior, just remove the conditional text.contains(",").

  • Our stayed top I will test and try to implement the other columns, thank you very much

  • 1

    @Claudio Voce can mark the answer as accepted, if she helped you ;)

  • Just a little question: if I want to take this typed data and store each one in a variable to make calculations with the numbers typed before showing in the table, I could take advantage of this method?

  • 1

    @Claudio If you notice in the Listener, soon after capturing the text of the field, I created a string array containing the values separated by comma in each of its indices, just use this array. Probably Voce will need to cast for integer, because even if they are numbers, they are strings.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.