let rowCount = 1;
function
setup() {
createCanvas(500, 400);
textSize(16);
addRowBtn = createButton(
"Add Row"
);
addRowBtn.position(30, 50);
addRowBtn.mouseClicked(addOneRow);
removeRowBtn =
createButton(
"Clear Last Row"
);
removeRowBtn.position(160, 50);
removeRowBtn.mouseClicked(clearLastRow);
table =
new
p5.Table();
table.addColumn(
"book"
);
table.addColumn(
"price"
);
showTable();
}
function
addOneRow() {
let newRow = table.addRow();
newRow.set(
'book'
,
"Book "
+ rowCount);
newRow.set(
'price'
,
"Price "
+
(rowCount * random(1, 10)).toFixed(1));
rowCount++;
showTable();
}
function
clearLastRow() {
let lastRow = table.getRowCount() - 1;
if
(lastRow >= 0)
table.removeRow(lastRow);
showTable();
}
function
showTable() {
clear();
text(
"Click on the buttons to change"
+
" the number of rows in the table"
,
20, 20);
let rowCount = table.getRowCount();
text(
"There are "
+ rowCount +
" rows in the table"
, 20, 100);
for
(let r = 0; r < rowCount; r++) {
let currRow = table.rows[r].arr.toString();
currRow = currRow.split(
", "
).join(
" "
);
text(currRow, 30, 140 + r * 20);
}
}