What you need to do is add a row to the Model
. Something like this
public void actionPerformed(ActionEvent arg0) {
DefaultTableModel model = (DefaultTableModel)table.getModel();
model.addRow(new Object[]{"DN Korina", "DN Madrid", "DN Romania"});
}
The easiest way is to set up you model before hand to have no rows
String[] colNames = {
"QTY", "Item Code", "Amount"
};
DefaultTableModel model = new DefaultTableModel(colNames, 0); <== 0 rows
JTable table = new JTable(model);
Then whatever rows you want to add, just add to the model
public void actionPerformed(ActionEvent e){
model.addRow(new Object[]{"DN Korina", "DN Madrid", "DN Romania"});
}
UPDATE Example
import java.awt.*;
import java.util.Stack;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class TestTable {
private String[] colNames = { "Col 1", "Col2", "Col3", "Col4", "Col5" };
private DefaultTableModel model = new DefaultTableModel(colNames, 0);
private JTable table = new JTable(model);
private MyStack myStack = new MyStack();
private Stack<Integer[]> stack;
private JButton button = new JButton("Add Row");
public TestTable() {
stack = myStack.getStack();
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!stack.isEmpty()) {
Integer[] array = stack.pop();
model.addRow(array);
}
}
});
JFrame frame = new JFrame();
frame.add(new JScrollPane(table), BorderLayout.CENTER);
frame.add(button, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new TestTable();
}
});
}
}
class MyStack {
public Stack<Integer[]> stack = new Stack<Integer[]>();
public MyStack() {
int k = 1;
for (int i = 0; i < 20; i++) {
Integer[] array = new Integer[5];
for (int j = 0; j < 5; j++) {
array[j] = i * k * (j + 1);
}
k++;
stack.push(array);
}
}
public Stack<Integer[]> getStack() {
return stack;
}
}
Explanation
- I have a MyStack class that has a
Stack
. It could be any data structure like an array even, but I chose to use a Stack
because I can just .pop()
it. And the get the Integer[]
.
- I instantiate that class in the GUI class
- I then extract that
Stack
. Keep in mind the Stack
holds Integer[]
's
- As i explained, you want to add a single dimension array to the
model
.
- So every time I click the button, an
Integer[]
is pulled out of the Stack
, then I just add that array to the model
as a row.