I using detaful table model
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
and I row count
int Row = model.getRowCount();
Here is which I add row and wish to diplay error when adding same items.
if (Row > 0) {
for(i=0;i<Row; i++){
if(jTable1.getValueAt(i,0).equals(name.getText())){
JOptionPane.showMessageDialog(null, "Can't add same item");
}
}
}else if (Row <99) {
model.addRow(new Object[] {name.getText(),address.getText(),Integer.parseInt(age.getText())});
}
I guess wrong at if else statement?
Because I can add the 1st row and I can't add for 2nd row.
Thanks for help
Not sure what you have in your other variables, but I guess you have a discrepancy between product_id and name, perhaps?
Wouldn't it be more like
if(jTable1.getValueAt(i,0).equals(name.getText())){
UPDATE:
Try rewriting it like this:
int Row = model.getRowCount();
int boolean exists = false;
for(i=0;i<Row; i++){
if(jTable1.getValueAt(i,0).equals(name.getText())){
JOptionPane.showMessageDialog(null, "Can't add same item");
exists = true;
break;
}
}
if (!exists && Row < 99) {
model.addRow(new Object[] {name.getText(),address.getText(),Integer.parseInt(age.getText())});
}
Related
So I have a function that populates JTable from my database.
I have here
public static TableModel resultSetToTableModel(ResultSet rs) {
try {
ResultSetMetaData metaData = rs.getMetaData();
int numberOfColumns = metaData.getColumnCount();
Vector<String> columnNames = new Vector<String>();
// Get the column names
for (int column = 0; column < numberOfColumns; column++) {
columnNames.addElement(metaData.getColumnLabel(column + 1));
}
// Get all rows.
Vector<Vector<Object>> rows = new Vector<Vector<Object>>();
while (rs.next()) {
Vector<Object> newRow = new Vector<Object>();
for (int i = 1; i <= numberOfColumns; i++) {
if(isObjectInteger(rs.getObject(i)) && i>1) //checks if the value is Integer else not and is past the first column
{
System.out.println(i+"="+rs.getObject(i));
String label = columnNames.get(i); //THE ERROR IS ON THIS PART
newRow.addElement(getValue((Integer) rs.getObject(i),label)); //gets the value of specific foreign key id from another table
}
else
{
System.out.println(i+"="+rs.getObject(i));
newRow.addElement(rs.getObject(i));
} //inside row (new Rows)
}
rows.addElement(newRow); //outside row
}
return new DefaultTableModel(rows, columnNames)
{
#Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
I have total 8 columns in my database the output of that System.out.println is:
The one's that get's inside the else:
1=1
2=test
3=A.
4=test
5=test
6=test
The one's that get's inside the if
7=1
8=23
As you can see the output is right but it always throws Array index out of range: 8 error on the String label = columnNames.get(i);
While ResultSet.getObject() requires an argument based on one, columnNames is a vector, with its indexes based on zero.
Hence valid values for it would be 0..7, not 1..8. In other words, the first part of your if statement should be:
System.out.println(i + "=" + rs.getObject(i));
String label = columnNames.get(i-1); // NOT "i".
I have a JTable2 in frame1 and JTable1 in frame2. I want to copy and send selected data from table2 to table1. how do i do it ?
private void jButton3MouseClicked(java.awt.event.MouseEvent evt) {
String sql = "select * from table1 where Bill_No like '"+jTextField2.getText()+"'";
try{
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
jTable2.setModel(DbUtils.resultSetToTableModel(rs));
JFrame NewJFrame2 = new NewJFrame2();
NewJFrame2.setVisible(true);
int i=0;
while(rs.next()) {
Object bno = rs.getString("Bill No");
Object bamount = rs.getString("Bill Amount");
Object btds = rs.getString("TDS");
Object btax = rs.getString("Tax");
Object bpayable = rs.getString("Payable");
jTable1.getModel().setValueAt(bno,i, 0 );
jTable1.getModel().setValueAt(bamount, i, 1);
jTable1.getModel().setValueAt(btds, i, 2);
jTable1.getModel().setValueAt(btax, i, 3);
jTable1.getModel().setValueAt(bpayable, i, 4);
System.out.println(i);
i++;
}
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
Start by having a look at How to Use Tables.
If you want to "copy" the selected data, then you will need to know what rows are selected, see JTable#getSelectedRows.
You're making life difficult for yourself using DbUtils as you've lost the ability to just transfer the objects from one model to another.
The basic idea would be to copy the values from the original table into a new TableModel and pass that to the second window, something like
TableModel original = table.getModel();
DefaultTableModel model = new DefaultTableModel(table.getSelectedRowCount(), original.getColumnCount());
for (int col = 0; col < original.getColumnCount(); col++) {
model.addColumn(original.getColumnName(col));
}
int[] selectedRows = table.getSelectedRows();
for (int targetRow = 0; targetRow < selectedRows.length; targetRow++) {
int row = selectedRows[targetRow];
int modelRow = table.convertRowIndexToModel(row);
for (int col = 0; col < original.getColumnCount(); col++) {
model.setValueAt(original.getValueAt(modelRow, col), targetRow, col);
}
}
for example. Now you just need to pass model to the second window and apply it to the JTable contained within
I have a button click event on which i am getting a column value, if a Table row is selected. But if i don't select the row and click the button i get the error: java.lang.ArrayIndexOutOfBoundsException:-1 my question is how can i check to see if a row has been selected pseudocode: if(Row == selected) { execute }
java code i have:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
try
{
int row = Table.getSelectedRow();
String Table_click = (Table.getModel().getValueAt(row, 0).toString());
//... implementation hire
} catch (Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
}
Thank you for your help.
Stop and think logically about your problem before you're tempted to post. Take a break from coding if you need to -- once you take a break, the solution to the problem often presents itself in short order.
int row = Table.getSelectedRow();
if(row == -1)
{
// No row selected
// Show error message
}
else
{
String Table_click = (Table.getModel().getValueAt(row, 0).toString());
// do whatever you need to do with the data from the row
}
When no row is selected, getSelectedRow() returns -1.
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
try {
int row = Table.getSelectedRow();
if (row > -1) {
String Table_click = (Table.getModel().getValueAt(row, 0).toString());
//... implementation here
}
}
catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
if row > -1 then you know a row has been selected.
see: http://docs.oracle.com/javase/7/docs/api/javax/swing/JTable.html#getSelectedRow()
How to prevent duplicate entries in JTable?
I want to stop enter duplicate data in table. I tried given below cord. But it is not working. My first column name is item id. So I used jtable.getValueAt(i, 1). It that wrong.
public void lordTable(JTable jtable, JTextField txtItemID, JTextField txtName, JTextField txtQty, JTextField txtUp) {
String s = "";
boolean exists = false;
for (int i = 0; i < jtable.getRowCount(); i++) {
s = jtable.getValueAt(i, 1).toString().trim();
if (txtItemID.getText().equals("")) {
JOptionPane.showMessageDialog(null, "Enter Invoice Details First");
} else {
if (txtItemID.getText().equals(s)) {
exists = true;
break;
}
}
}
if (!exists) {
DefaultTableModel dd = (DefaultTableModel) jtable.getModel();
Vector v = new Vector();
v.add(txtItemID.getText());
v.add(txtName.getText());
v.add(txtQty.getText());
v.add(txtUp.getText());
Double val = (Double.parseDouble(txtUp.getText())) * (Double.parseDouble(txtQty.getText()));
v.add(val);
dd.addRow(v);
} else {
JOptionPane.showMessageDialog(null, "data already exist.");
}
}
Access first column in a table with zero, that is: getValueAt(row, 0).
How to get row with index i froj JTable ? I looked at member functions but there is nothing like getRowAt . Can anybody help ?
There is no "row" object for a table, so nothing you could get with a getRow method.
You can ask getValueAt() to get the individual values, use it for each column and you have your complete row.
AFAIK, there is no such method. Write something like that:
public String[] getRowAt(int row) {
String[] result = new String[colNumber];
for (int i = 0; i < colNumber; i++) {
result[i] = table.getModel().getValueAt(row, col);
}
return result;
}
P.S - Use table.getValueAt() if you want to respect a rearranged by the user column order.
I recommend to create a TableModel based on a list of POJOs.
It's then easy to add a method like:
MyPojo getData(int index);
Have a look at this sample I wrote some time ago for a starting point:
http://puces-samples.svn.sourceforge.net/viewvc/puces-samples/tags/sessionstate-1.0/sessionstate-suite/sessionstate-sample/src/blogspot/puce/sessionstate/sample/ParticipantTableModel.java?revision=13&view=markup
Try something like this
private void getIndexRow(){
int i;
int row = 0;
int column = 0;
i=Integer.parseInt(myTable.getValueAt(row,column).toString());
}
Another way of doing it is using the table model's getDataVector() method.
DefaultTableModel tm = (DefaultTableModel) table.getModel();
Vector<Object> rowData = tm.getDataVector().elementAt(rowIndex);
private void jTable1MousePressed(java.awt.event.MouseEvent evt) {
int selectedRow;
ListSelectionModel rowSM = jTable1.getSelectionModel();
rowSM.addListSelectionListener(new ListSelectionListener()
{
#Override
public void valueChanged(ListSelectionEvent e)
{
ListSelectionModel lsm = (ListSelectionModel) e.getSource();
selectedRow = lsm.getMinSelectionIndex();
int numCols = jTable1.getColumnCount();
model = (DefaultTableModel) jTable1.getModel();
System.out.print(" \n row " + selectedRow + ":");
for (int j = 0; j < numCols; j++)
{
System.out.print(" " + model.getValueAt(selectedRow, j));
}
}
});
}
Using this you can get value of whole row where u click on particular row.
This function is working well for me.
private Object[] getRowAt(int row, DefaultTableModel model) {
Object[] result = new Object[model.getColumnCount()];
for (int i = 0; i < model.getColumnCount(); i++) {
result[i] = model.getValueAt(row, i);
}
return result;
}