How to display a 2D array in jTable? - java

I have a static 2D array called Status.Data[][] and a Column header called Status.Columns[].
I am using net beans and I want to be able to have the arrays populate the table.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
jTable1.setColumnModel(new DefaultColumnModel(Status.Data, Status.Columns));
}
This throws an error that it is expecting a TableColumnModel.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
jTable1.setColumnModel(new TableColumnModel(Status.Data, Status.Columns));
}
This says java.swing.table.TableColumnModel is abstract and cannot be instantiated.
I would even be happy if I could figure out how to make it display when the window is opened.
How do I populate my table?

You can create the table model and then pass it to the table constructor:
TableModel model = new DefaultTableModel(Status.Data, Status.Columns);
JTable table = new JTable(model);

use javax.swing.table.DefaultTableModel
DefaultTableModel(Object[][] data, Object[] columnNames)

Related

java jtable replacing the old value with the new value

i am facing the problem while i am running my project. The situation is, i have a button which let me to print the output in the table. However, every time i click on the button, the table is appending rather than replacing the old value. For jtextarea i solved it using a simply way which is use jtextarea.settext rather thn jtextarea.append. This is how i passing the value in to the table DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
model.addRow(row);
i declare row as vector. Can anyone tell me how to make it replace the value rather than append.
As shown here, invoke setRowCount(0) to clear the table's model and then model.addRow(row) to add a new row.
i use like this... and it's work for me
i use Netbeans IDE
public class test extends javax.swing.JFrame {
DefaultTableModel model ;
public test() {
initComponents();
model = (DefaultTableModel) table.getModel();
}
private void initComponents() {..}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
Object[] a = {"insert","test"};
model.addRow(a);
}

Updating JTable on button click

I am working with a JTable with a Custom Table Model found here. I have updated my code with the suggestions provided in that post and have run into a new problem. The change I have made to my code was to inject an ArrayList<CompletedPlayer> into my JTable to avoid issues with threads. After doing that, the code to update my table by pressing a button has stopped working.
The code used to initialize the JTable is the following:
TableModel model = new PlayerTableModel(FileHandler.getCompletedPlayers());
JTable table = new JTable(model);
The code I used to update the JTable is the following:
JButton btnRefreshAllPlayers = new JButton("Refresh");
btnRefreshAllPlayers.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
PlayerTableModel model = (PlayerTableModel) table.getModel();
model.fireTableDataChanged();
}
});
I have also tried using repaint() but this does not work either. As of right now, the only way to get the JTable to update is to close and reopen the program. FileHandler has the ArrayList I am using for the JTable which increases in size as the user adds more players.
Why doesn't fireTableDataChanged() detect any changes?
I have searched on stackoverflow and a couple of people have said to use that method.
No, you should not call any fireTableXxx methods outside of the context of the TableModel itself, people suggesting otherwise are simply wrong and it will cause you issues in the future. From the looks of your code, nothing has changed. If you've updated the TableModel according to the answer provided in your previous question, then there is no relationship with the data in the model to the external source. You need to manually reload the data from the external source, create a new TableModel and apply it to the table
For example...
JButton btnRefreshAllPlayers = new JButton("Refresh");
btnRefreshAllPlayers.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
TableModel model = new PlayerTableModel(FileHandler.getCompletedPlayers());
table.setModel(model);
}
});
I have also tried setting a new model with the updated ArrayList and it worked but did not keep the table row widths I previously set.
This is a reasonable thing for the table to do, because it has no idea if the new model has the same properties/columns as the old, so it resets them.
You could walk the ColumnModel, storing the column widths in a List or Map before you apply the model and reapply the widths
Is there a proper way to update the JTable?
You could provide your TableModel with a refresh method, which could load the data itself and trigger a tableDataChanged event
public class PlayerTableModel extends AbstractTableModel {
private final List<PlayerSummary.Player> summaries;
public PlayerTableModel(List<PlayerSummary.Player> summaries) {
this.summaries = new ArrayList<PlayerSummary.Player>(summaries);
}
// Other TabelModel methods...
public void refresh() {
summaries = new ArrayList<>(FileHandler.getCompletedPlayers());
fireTableDataChanged();
}
}
Then you would need to call this method in your ActionListener...
PlayerTableModel model = (PlayerTableModel)table.getMode();
model.refresh();

Refreshing the java Jtable to show updated data

I am trying to refresh my Jtable shown in the UI whenever I query the mysql database. The idea was to show whatever new data updated in the UI JTable.
The UI class is below.
public class DBView {
private JFrame frame = new JFrame();
private JScrollPane tableScrollPane = new JScrollPane();
private DefaultTableModel dbTable = new DefaultTableModel();
public void setDbTable(DefaultTableModel dbTable) {
this.dbTable = dbTable;
//this.dbTable.repaint();
paintDBTable();
}
public DefaultTableModel getDbTable() {
return dbTable;
}
public DBView() {
initializeFrame();
paintDBTable();
}
private void paintDBTable() {
tableScrollPane.setBounds(20, 350, 400, 80);
frame.getContentPane().add(tableScrollPane);
JTable DBTable = new JTable(dbTable);
tableScrollPane.add(DBTable);
DBTable.setFillsViewportHeight(true);
tableScrollPane.setViewportView(DBTable);
}
/**
* Initialize the contents of the frame.
*/
private void initializeFrame() {
frame.setVisible(true);
frame.setBounds(100, 100, 451, 525);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
frame.setTitle("MySQL Database");
}
From another Model class I am calling the setDbTable() method. I input a new Jtable object to the setDbTable() method with data read from the database input into the new Jtable object.
The issue is inside the setDbTable() method, I am using paintDBTable() method again.
I tried using dbTable.fireTableDataChanged() method to refresh the view, didnt work.
The way it is now, it is working. But using the setDbTable() method to refresh seems like a very inefficient way to do it.
Question is Do you see anyway I could use another method defined for use of refreshing Jtables?
P.S. I am very new to java and programming in general. Sorry if the code is messy and the question is unclear. I can give all the code if its helpful. I removed most of the methods and other classes in the original code to make the question clearer.
tableScrollPane.add(DBTable);
JScrollPane isn't designated as container, you have to add child to JViewport
there are two options
a) tableScrollPane = new JScrollPane(myTable);
b) tableScrollPane.setViewportView(myTable);
DefaultTableModel dbTable = new DefaultTableModel();
DefaultTableModel is model that hold value for presentations layer for the JTable
rename this local variable (that make the sence) to dbTableModel instead of dbTable
you have to create a JTables view, f.e. two basics options
a) JTable myTable = new JTable(dbTableModel)
b) myTable.setModel(dbTableModel)
dbTable.fireTableDataChanged() is implemented in DefaultTableModel and correctly, not reason to call this method, nor outside of models definition (class, void, interface that returns XxxTableModel)
more informations in linked Oracle tutorials, ... for working code examples in SSCCE / MCVE form too
refresh data for JTable by
removing all rows in dbTableModel.setRowsCount(0);, then add a new row(s) to dbTableModel.addXxx
re_creating dbTableModel, note then must be added back to JTable e.g. myTable.setModel(dbTableModel)
It is not so confusing to refresh the JTable data and refreshing the UI after that, because:
Swing components implemented MVC and Observer in a very fantastic way. That means whenever you change the data in TableModel, the UI will be notified and repainted as you wanted.
So you should change you code in a way that you keep the JTable variable not the TableModel variable in your class. After that in setDbTable call the setModel method of the JTable, it means:
public class DBView {
private JTable jtable = new JTable();
public void setDbTable(DefaultTableModel dbTable) {
this.jtable.setModel(dbTable);
//this.dbTable.repaint();
//paintDBTable();
}
.
.
.
}
Hope this would be helpful,
Good Luck.

Dynamically updating jTable

My table will change the entire dataset during runtime.
My current code looks like below,
public class gui_test_form extends JFrame{
private JPanel rootpanel;
private JTable testTable;
private JScrollPane testScrollPane;
private JButton testButton;
private String[] columnNames = {"Name", "Color"};
private Object[][] data = { {"John", "Blue"}, {"Oliver", "Green"}, {"Paul", "Red"} };
public gui_test_form() {
super("GUI TEST");
setContentPane(rootpanel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
testButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent actionEvent) { // Button Clicked
//Get new values
data[0][0] = "New Value";
//Update table
testTable.setModel(new DefaultTableModel(data, columnNames));
}
});
}
}
The code works as I expected. But I don't think making a new DefaultTableModel everytime is the best way to go. What should I be doing?
I looked briefly into fireTableChanged() method for AbstractTableModel, but couldn't make it work. I expected it would work since DefaultTableModel is inherited from AbstractTableModel.
Any help is appreciated.
-------Edit-------
Forgive me if I wasn't clearer before, but the problem is that I want to update the whole dataset. Even the Column names and the number of columns and rows are going to change.
For example, in the above code I could do this, and it would still work as you'd expect.
//Get new values
columnNames = new String[]{"Country", "Location", "Latitudes"};
data = new Object[][]{ {"John", "Blue", "1"}, {"Oliver", "Green", "4"}};
//Update table
You should be declaring a single table model at the same level where you create your JTable and making changes to that table model as required, rather than declaring it in the event handler.
private JPanel rootpanel;
private JTable testTable;
private DefaultTableModel tableModel;
private JScrollPane testScrollPane;
private JButton testButton;
tableModel = new DefaultTableModel();
testTable = new JTable(tableModel);
Take a look at the Java Tutorial. Pay attention to the section on listening for table data changes
If you come up with your own table model, you need to be sure to fully implement all overridden methods, particularly setValueAt(), and make sure you keep track of your row count properly. One of the most common mistakes involves forgetting to increment your row count after adding data and thinking that the table model is not receiving data.
Add below code in wherever you want to update the model.
model.addRow(new Object[]{txt_title.getText(), txt_name.getText()});
Before, The model and table must also be predefined globally.
DefaultTableModel model = new DefaultTableModel();

JTable not updating when model updates

Ok, I have read up on this, but I'm still very confused. I have a JTable with a custom Table Model that stores data in an ArrayList. It displays just fine. However, when I want to add a row, I add an object to the ArrayList, then call fireTableRowsInserted(...). However, the table does not refresh.
public Main() {
initComponents();
current_map = new Map();
current_map.authors.add(new Author("New Author"));
author_model = new AuthorModel(current_map.authors);
jTable1.setModel(new AuthorModel(current_map.authors)); <---This is the mistake
}
...
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
author_model.authors.add(new Author("New Author"));
author_model.fireTableRowsInserted(author_model.authors.size(), author_model.authors.size());
}
The above code is from my main JFrame. Not sure where to go from here.
I'm lost right now.
The table is initialized with:
jTable1.setModel(new AuthorModel(current_map.authors));
But when the button is clicked, you modify the variable author_model:
author_model.authors.add(new Author("New Author"));
The initialization of the table should be
jTable1.setModel(author_model);
You should also respect the Java naming conventions, and choose better names for your variables.

Categories