简体   繁体   中英

How to add new Row by clicking in a jTable?

I have created a java program in which:

A user can input data by using a custom JOption showConfirmDialog box (with added panel and textboxes)

I've used a separate method for the user input

public static String[] MultiInput(){

  JTextField idField = new JTextField(5);
  JTextField nameField = new JTextField(5);
  JTextField addressField = new JTextField(5);
  JTextField ageField = new JTextField(5);

  JPanel myPanel = new JPanel();
  myPanel.add(new JLabel("ID number:"));
  myPanel.add(idField);
  myPanel.add(Box.createHorizontalStrut(15)); // for  spacing
  myPanel.add(new JLabel("Name:"));
  myPanel.add(nameField);
  myPanel.add(Box.createHorizontalStrut(15)); // for  spacing 
  myPanel.add(new JLabel("Address:"));
  myPanel.add(addressField);
  myPanel.add(Box.createHorizontalStrut(15)); // for  spacing
  myPanel.add(new JLabel("Age:"));
  myPanel.add(ageField);

  int result = JOptionPane.showConfirmDialog(null, myPanel, 
           "Please Enter Data Here:", JOptionPane.OK_CANCEL_OPTION);
  if (result == JOptionPane.OK_OPTION) {
      String[] Input={idField.getText(),nameField.getText(),addressField.getText(),ageField.getText()};

      return Input;
  }
    return null;
}

and calls this method once the user clicks a row on the jTable

 private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {        

   int row = jTable1.getSelectedRow();
    String[] input;
    input =MultiInput(); // get input from user

    for(int ctr=0;ctr<jTable1.getColumnCount();ctr++){
       jTable1.setValueAt(input[ctr], row, ctr);

    }

The user fills in the TextFields and after clicking "OK", sets the value in the selected row in the jTable.

The Problem is I want to create a new row for the input if the user clicks the jTable

EDIT:

This is how I created my jTable and Table Model

final DefaultTableModel model = new javax.swing.table.DefaultTableModel(
new Object [][] {                                                   
    {null, null, null, null},
    {null, null, null, null},
    {null, null, null, null},
    {null, null, null, null}

},
new String [] {
    "idnum", "name", "adress", "age"
}
    );
jTable1 = new javax.swing.JTable();

jTable1.setAutoCreateRowSorter(true);

jTable1.setModel(model);

jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
 public void mouseClicked(java.awt.event.MouseEvent evt) {
    jTable1MouseClicked(evt);
 }
});

jScrollPane1.setViewportView(jTable1);

To add a row to a jTable you can simply use this. Keep in mind that the input must be an array.

DefaultTableModel tableModel = (DefaultTableModel) table.getModel(); tableModel.addRow(input);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM