Olá, pessoal. Dei uma olhada pelo fórum e percebi que meu problema é bem simples: estou usando DefaultTableModel… Na verdade, meu problema é que mesmo alterando o conteúdo da tabela (inserindo linhas, no caso), o view da tabela não é atualizado. Tentei repaint, update, pack do frame, mas nãoi funcionou. Declarei explicitamente fireTableUpdate() entre outra chamadas. Ok. Estou disposta a mudar de model, criando o meu próprio, extendendo o AbstractTableModel.
A questão então é a seguinte, eis o código:
package table;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableModel;
import java.awt.Dimension;
import java.awt.GridLayout;
public class Demo4 extends JPanel {
private static JTable table;
private static JFrame frame = new JFrame("TableSelectionDemo");
private static DefaultTableModel model;
private static Demo4 newContentPane = new Demo4();
public Demo4() {
super(new GridLayout(1,1));
//creating the model and table
model = new DefaultTableModel();
table = new JTable(model);
//the creation of the columns
model.addColumn("Edge Label");
model.addColumn("Source");
model.addColumn("Destination");
model.addColumn("Bandwith");
//adjusting the size of the window
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.setFillsViewportHeight(true);
table.setCellSelectionEnabled(true); //permite que seja selecionada uma célula por vez
//create the scroll pane and add the table to it.
JScrollPane scrollPane = new JScrollPane(table);
//add the scroll pane to this panel.
add(scrollPane);
model.addRow(new Object[]{"edge1", "123.456.789.101", "234.567.891.011", 50});
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
* @throws InterruptedException
*/
private static void createAndShowGUI() {
//Disable boldface controls.
UIManager.put("swing.boldMetal", Boolean.FALSE);
//Create and set up the window.
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
}
/**
* tableSetValueAt is a public method to be able to insert a new value in a single cell
* of the created table.
* @param valor -> value to be inserted
* @param linha -> row of the cell to be modified
* @param coluna -> column of the cell to be modified
*/
public void tableSetValueAt(int valor, int linha, int coluna){
table.setValueAt(valor, linha, coluna);
}
/**
* tableAddRow is a public method to be able to insert new rows in the created table.
* As you can see, it's not the table itself that is modified, but the model.
* @param rowData -> the row of data to be inserted. Pay attention, because this row
* should contain the exact amount data as the number of columns in the table
*/
public void tableAddRow(Object[] rowData){
model.addRow(rowData);
}
public void createView() {
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
Agora a classe de teste:
import table.Demo4;
public class Demo41 {
public static Demo4 tent = new Demo4();
public static void main (String args[]) throws InterruptedException{
int r=0, c=0, v = 0;
Object[] row1 = new Object[]{"edge1", "123.456.789.101", "234.567.891.011", 50};
Object[] row2 = new Object[]{"edge2", "123.456.789.101", "234.567.891.021", 50};
Object[] row3 = new Object[]{"edge3", "234.567.891.011", "234.567.891.021", 50};
tent.createView();
tent.tableAddRow(row1);
tent.tableAddRow(row2);
tent.tableAddRow(row3);
Thread.sleep(2000);
for(int n=0; n < 5; n++){
if (n%2 == 0){
v++;
tent.tableSetValueAt(v, c, r);
c++;
r++;
Thread.sleep(1000);
}
}
}
}
Esclarecendo algumas coisas do código: esse for com Thread.sleep(1000) é para simplesmente dar tempo do view ser renderizado corretamente e simular um ambiente em que os dados são atualizados em tempo real (é asism que a classe será utilizada).
Para que eu implemente esse novo model, além dos gets que devem ser implementados, os dois métodos de modificação de tabelas seriam:
public void setValueAt(Object data, int row, int column){
table.setValueAt(data, row, column);
model.fireTableCellUpdated(row, column);
}
e este outro:
public void addRow(Object[] rowData){
model.addRow(rowData);
model.fireRowsInserted(0, table.getRowCount());
}
ou algo mais seria necessário para resolver meu problema de atualizar o view da JTable? Espero que tenha ficado tudo bem claro…
Abraços!
Ps.: seria possível utilizar o model que o mark/viniGodoy utilizam para resolver meu problema também?
