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);
TableModel
to add rows. What type ofTableModel
are you using? Maybe have a look at How to Use Tables – MadProgrammerDefaultTableModel
(making sure you apply it to theJTable
), when you need to use one of theadd
methods of theDefautTableModel
to add new data to it. It will automatically update the table – MadProgrammer