JTable won't refresh - java

Why won't table cell 0,1 change from aaa to XXXX?
import java.awt.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
class MainFrame {
public static void main(String[] args) {
JFrame f = new JFrame("Refreshing JTable");
JPanel p = new JPanel(new GridBagLayout());
DefaultTableModel productsModel;
JTable productsTable;
f.setSize(800, 600);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
String[] tableTitle = new String[] {"ID", "Name"};
String[][] tableData = {{"1", "AAA"},{"2", "BBB"}};
productsModel = new DefaultTableModel(tableData, tableTitle);
productsTable = new JTable(productsModel) {
public boolean isCellEditable(int r, int c) {
return false;
}
};
JScrollPane scrollpane = new JScrollPane(productsTable);
tableData[0][1] = "XXXX";
f.add(p);
p.add(scrollpane);
f.validate();
f.setVisible(true);
}
}
REASON:
Apparently trying to update the array where data is stored will result in JTable not changing. Either DefaultTableModel needs to be updated or the whole table needs to be redrawn.
EDIT (possible Solution) One way is using Timer:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
class MainFrame {
static JFrame f = new JFrame("Refreshing JTable");
static JPanel p = new JPanel(new GridBagLayout());
static DefaultTableModel productsModel;
static JTable productsTable;
public static void main(String[] args) {
runGui();
}
#SuppressWarnings("serial")
public static void runGui() {
f.setSize(800, 600);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
String[] tableTitle = new String[] {"ID", "Name"};
String[][] tableData = {{"1", "AAA"},{"2", "BBB"}};
productsModel = new DefaultTableModel(tableData, tableTitle);
productsTable = new JTable(productsModel) {
public boolean isCellEditable(int r, int c) {
return false;
}
};
JScrollPane scrollpane = new JScrollPane(productsTable);
tableData[0][1] = "XXXX";
Timer t = new Timer(2000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
addColumns();
remakeData();
productsTable.setModel(productsModel);
}
});
t.start();
f.add(p);
p.add(scrollpane);
f.validate();
f.setVisible(true);
}
private static void addColumns() {
productsModel.setColumnCount(0);
productsModel.addColumn("ID");
productsModel.addColumn("Name");
}
private static void remakeData() {
productsModel.setRowCount(0);
productsModel.insertRow(productsModel.getRowCount(), new Object[] {"1", "Dummy item 1"});
productsModel.insertRow(productsModel.getRowCount(), new Object[] {"2", "Dummy itme 2"});
productsModel.insertRow(productsModel.getRowCount(), new Object[] {"3", "Dummy item 3"});
productsModel.insertRow(productsModel.getRowCount(), new Object[] {"4", "Dummy item 4"});
productsModel.insertRow(productsModel.getRowCount(), new Object[] {"5", "Dummy item 5"});
}
}
EDIT(much better solution, the way it worked for me flawlessly) Using a static method. Since I'm adding new data in array through another Frame, I created a static method in MainFrame, which I call every time I add/update/delete Object in array. This method will redo the whole model after update and will therefore refresh table.

One problem with the SSCCE posted on your related thread is that the code changes the array which originally formed the table model, whereas it should be changing the table model itself.

The solution to your problem (and the previous one) is rather simple, but unfortunately a bit too long to post it in a comment
You make sure you do some reading on how a JTable actually works. A good starting point is the Swing tutorial and perhaps even the class javadoc of the most important classes JTable and TableModel. Another good read about Swing and the use of MVC is this document. It is much broader then only JTables but will provide you with more insight in how all Swing components are designed, and how you should use them.
After reading that tutorial, you should understand that if you want to update the data which is shown in the table, you update the model of your table. The model will fire events which are received by the table, and the table will make sure it updates itself. After all, the table is only a view on the data (=the TableModel) so updates on the take should take place on the model side. If this is not clear, go back to step 1
Now take a look at your code and remove the listener. Instead, update the model on the table and see how the table updates itself.
If this does not work, you come back to this site with an SSCCE which you post. That way we can see that you tried something, what you tried and most likely what is wrong in your code. This SSCCE should include your code of the TableModel you use and the code that updates your TableModel since that is the most likely location for your problem.

Related

Cannot build, or show, a Swing JTable with checkboxes inside a JScrollPane

I am building up a very simple contact book. I am trying to realize a table with checkboxes for each of user's contact list. I am basing on this: https://stackoverflow.com/a/7392163/6528351. I have edited a little bit that code, choosing (UserContactTablePane) to extend the JScrollPane and use it as container of the table [EDIT 2: code edited to fit a hard code version]:
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;
public class RubricaMain {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
RubricaGui frame = new RubricaGui();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
class RubricaGui extends JFrame implements ActionListener {
public RubricaGui() throws IOException {
this.setResizable(false);
setTitle("Contact book");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setShowRubricaFrame(this);
}
#Override
public void actionPerformed(ActionEvent e) {
}
private void setShowRubricaFrame(JFrame main) {
main.setBounds(250, 100, 1000, 355);
JPanel panel = new JPanel();
panel.setLayout(null);
main.setContentPane(panel);
main.setVisible(true);
Object[] columnNames = {"", "Name", "Surname", "Telephone number", ""};
Object[][] dataTable = {
{"1","Harry","Kane","+44 333333",false},
{"2","David","Bechkam","+44 444444",false},
{"3","Steven","Gerrard","+44 555555",false}
};
JScrollPane scrollingContactsPanel = new UserContactTablePane(columnNames, dataTable);
scrollingContactsPanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Contact book", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
scrollingContactsPanel.setBounds(10, 50, 975, 260);
panel.add(scrollingContactsPanel);
}
}
class UserContactTablePane extends JScrollPane {
private JTable table;
public UserContactTablePane(Object[] columnNames, Object[][] data) {
DefaultTableModel model = new DefaultTableModel(data, columnNames);
table = new JTable(model) {
#Override
public Class getColumnClass(int column) {
switch (column) {
case 0:
return String.class;
case 1:
return String.class;
case 2:
return String.class;
case 3:
return String.class;
default:
return Boolean.class;
}
}
};
table.setPreferredScrollableViewportSize(table.getPreferredSize());
}
}
I am not managing to create and show it.
The method setShowRubricaFrame sets up the main frame inside which showing the telephone number list of a user, list that I pass as an Object[][] to UserContactTablePane.
I don't know what I am missing. The scroll pane with the table does not get created (shown).
Might I ask for your help, please? Thanks.
EDIT 1 - the scroll pane "Rubrica" should show my list, but it does not:
I didnt know that now it is mandatory to copy-paste all executable code.
If you make an effort to ask a good clear question we will make an effort to give a good answer
In any case you have NOT been asked to post all the executable code. You have been asked to post an MRE which is completely different. The point of the MRE is for you to make sure you understand the question you are asking by simplifying the code.
Your question is How to I add a JTable to a JFrame. 90% of the code you posted is completely irrelevant to that question. It does not matter where the data comes from. That is that data can be hard coded, which means the SQL logic is completely irrelevant to your stated problem.
It takes one line of code to create a JTable:
JTable table = new JTable(10, 50);
So figure out how to add that table to your frame first. Then later you worry about creating a TableModel from data in your database. Learn to walk before you run. It is easier to debug 10 lines of code that it is 100. So your first task is to simplify the problem.
With a quick glance at the code (there is too much code posted to look at it in detail) I see some problems:
Using a null layout is wrong. Swing was designed to be used with layout managers.
When you create your Rubrica frame you pass a reference to the previous frame, why? Once the user is logged in thee is no need to reference that frame. Instead I would pass the "user". Then you can use the user to do your SQL query.
Don't extend JScrollPane!!! You are not adding any new functionality to the scrollpane. In fact this may be your main problem. You extend the scrollpane and create a JTable, but you never add the JTable to the scrollpane. Get rid of that class and just create your table and the scroll pane in the constructor of your class.
Swing components should be added to the frame BEFORE the frame is made visible.

How to refresh JTable with always-changing tableModel?

2015.5.5 22:11 updated. I found that, when I create a sorter and call setRowSorter() method in the MyTable's construction, afterwards, it
will keep the original line number(in which the data still refresh
correctly but not easy to discover)even though the dataModel inside is
already changed many times which can be proven as
printf(getModel().getRowCount()). What's more,
MyTable.getAutoCreateRowSorter() always return true. I must explicitly
call setAutoCreateRowSorter(true) to fix the issue it if I called
setRowSorter(). I am happy but this is still wierd.
[2015.5.5 6:19 updated] I have found a way to access: make a "setRow" with the combination of insertRow() and removeRow() and everytime I
update, I setrRow all the rows in the table. It reflect immediately in
the UI. BUT there will be a series of error begin with "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Invalid index" and I guess it's about some kiind of swing thread problem because I can see "RepaintManager" or "paint" in the error. It occurs especially when I move the scrollbar when it's running.(but it still occur if I don't move it)
I have a JTable in a JScrollPane in a JFrame. I initial a MyTableModel with a data and use it to Create a JTable.Like this
MyTableModel extends DefaultTableModel{
Data data;
//object
MyTableModel (Data a){
data = a;
// do something to initial the table model,like build object[][] and add rows.
}
}
class main{
MyTableModel tm = new MyTableModel(data);
Jtable table = new JTable(tm);
JScrollpane jsp = new JScrollpane(table);
JFrame window = new JFrame();
window.getxxxpane().add(jsp);
}
So, as my data is always changing/updating and the changed row is plural and impossible to caculate.
while(true){
data.change();
refreshing the table to display the data immediately;
}
my idea is to simply build a new MyTableModel object and set it as the table's model like:
table.setModel(new MyTableModel(data)); //data had been changed.
which doesn't work.
and I tried this:
tm = MyTableModel(data);
tm.fireTableDataChanged();
which doesn't work either.
and the combination as well:
MyTableModol nm = new MyTableModel(data); //data had been changed
table.setModel(nm);
nm.fireTableDataChanged();
Could someone please give me some clue to change the TableModel object in an unchangable Jtable and update everytime.I dont want to change the tableModel Object because the calculation is huge, instead ,i Want to always create a new object with the construction method's parameter(changed data).
the most worst method is to remove the JScrollpane and rebuild one table/tablemodel/jscrollpane and re-add it, in which I have to call window.setVisible(true). window.repait() doesn't work,either,unless I move it.
I create a space-wasting but runnable program for demostration ,which most of them are nonsense.
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Formatter;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
class TM extends DefaultTableModel {
int[] inside;
static String[] columnNames = { "Hellium", "Radon",
};
TM(int[] data) {
super(columnNames, 0);
this.inside = data;
update();
}
void update() {
Object[][] data = new Object[2][columnNames.length];
for (int i = 0; i < 2; ++i) {
data[i][0] = inside[0];
data[i][1] = inside[1];
// setValueAt(aValue, row, column);
addRow(data[i]);
}
fireTableDataChanged();
}
}
class idkName {
TM tm;
JButton jb, jb2;
int data[] = { 1, 2 };
int data2[] = { 9, 10 };
JTable table;
JScrollPane jsp;
JFrame twindow;
idkName() {
JFrame window = new JFrame();
window.setSize(400, 400);
window.setLayout(new BorderLayout());
jb = new JButton("show");
jb2 = new JButton("change model");
window.add(jb, BorderLayout.EAST);
window.add(jb2, BorderLayout.WEST);
twindow = new JFrame();
jb.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
tm = new TM(data);
table = new JTable(tm);
jsp = new JScrollPane(table);
twindow.getContentPane().add(jsp);
twindow.setSize(500, 500);
twindow.setVisible(true);
}
});
window.setVisible(true);
jb2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
// tm = new TM(data2);
tm = new TM(data2);
System.out.println(""+tm.getValueAt(0,0));
tm.fireTableDataChanged();
twindow.setVisible(true);
}
});
}
}
public class main2 {
TM tm;
public static void main(String[] args) {
idkName i = new idkName();
}
}
If you're going to extend DefaultTableModel, then when the data is changed, you need to update it in DefaultTableModel's internal representation using the setValueAt or setDataVector methods. If you have extensive changes (which it sounds like you do), use the setDataVector method to change all the cells and the table structure at once. Your example code looks like it's missing some updates because it's not pushing the new values in to the DefaultTableModel's data vectors.
But since you have a lot of updates, you're probably better off avoiding DefaultTableModel and just extending AbstractTableModel, using your own custom data storage, and calling the appropriate fireXxx() methods whenever your data changes. This will probably be more efficient in terms of both data conversion and number of events raised.
And then make sure all the event and value change work is done on the AWT event thread, using SwingWorkers or other threading support.

Refresh table's row (Not row's value) on frame?

Sorry for being so amateur, I created a 'button' on a frame so that when we click the button for the first time, A ROW will be inserted on the frame. But ALL I WANT is that when I click the button THE SECOND TIME, the ROW IS REFRESHED (Not creating a new row!), I know that '.addRow(new Object[] { "", "", ""});' is the cause , because the object is created every time I click the button, so how could I possibly modify the code? Thanks for your attention.
*My weak brain said that if only I can empty 'model' object (or destroying the object, something like that), then I would find the solution, but how I could possibly empty/destroy that 'model' object?
import javax.swing.*;
import java.awt.event.*;
import javax.swing.table.DefaultTableModel;
public class MyTable extends JFrame {
private JTable table;
private DefaultTableModel model;
private JScrollPane scroll;
private JButton createRow;
private String headers[] = {"a", "b", "c"};
public MyTable() {
createRow = new JButton("Create Row");
model = new DefaultTableModel();
model.setColumnIdentifiers(headers);
table = new JTable();
table.setModel(model);
scroll = new JScrollPane(table);
add(createRow, java.awt.BorderLayout.NORTH);
add(scroll, java.awt.BorderLayout.CENTER);
createRowOn();
}
// while button is pressed then create A ROW
public void createRowOn() {
createRow.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == createRow) {
model.addRow(new Object[]{"", "", ""});
}
}
});
}
public static void main(String args[]) {
MyTable t = new MyTable();
t.setVisible(true);
t.setSize(300, 300);
}
}
Sorry for being so amateur
please read Oracle tutorial How to use Tables, especially part Creating Table Model
I created a 'button' on frame so that when we click the button for the
first time, A ROW will be inserted on frame. But all i want that when
i click the button on THE SECOND TIME , the ROW IS REFRESHED (Not
creating a new row !) , i suspect 'new Object[] { "", "", ""}' is the
cause , because the object is created everytime i click the button, so
how could i possibly modify the code ?
not clear from question (nothing is added to JTable) if you want to:
add a new row (model.addRow)
remove all rows (setDataVector/setRowCount)
reset value in JTables view (setValueAt)
but everything is described in Oracle tutorial, rest in the DefaultTableModel

addRow to DefaultTableModel in a separate class Eclipse

I have created a DefaultTableModel that is showing a very basic user league table in a JTabbedPane.
I want to add a row using some data I collect from a different class. This code will not run but here is a sample:
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class Statistics extends JPanel {
public Object[][] data;
public Statistics() {
super(new GridLayout(1,0));
String[] columnNames = {"Name", "Games Played", "Games Won"};
Object[][] data = {
{"Tom", new Integer(5), new Integer(2)},
{"Steve", new Integer(2), new Integer(0)},
};
DefaultTableModel model = new DefaultTableModel(data, columnNames);
JTable table = new JTable(model);
table.setFillsViewportHeight(true);
table.setVisible(true);
table.setEnabled(false);
JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane);
}
}
then I call this from my main class:
...
stats = new JPanel(); //create a new JPanel for table to go on
...
tp.addTab ("Statistics", stats); // add panel to JTabbedPane
..
leagueTable = new Statistics();// add the table to the stats panel
stats.add(leagueTable);
this is showing up and its fine, but can anyone guide me as to what syntax I use to add a row, I have tried:
leagueTable.addRow(table.getRowCount(), new Object[]{"ange", 5, 3});
but this does not work, eclipse asks me to add a method called 'addRow' to Statistics class, but I thought 'addRow' was already a method of DefaultTableModel, so I am very confused. Can anyone help me out on how to add a row of data to the table? Thanks IA
addRow is a method of the TableModel but you're invoking the method on the Statistics class. You could create a new method to add the data:
public class Statistics extends JPanel {
private DefaultTableModel model
public Statistics() {
super(new GridLayout(1,0));
model = new DefaultTableModel(data, columnNames);
...
}
public void addData(Object[] data) {
model.addRow(data);
}
}
Side note: Typically you don't want to extend JPanel here if not adding new functionality so a redesign is probably in order
leagueTable is an instance of your Statistics class. So it doesn't have an addRow() method.
Possible solution:
Make your DefaultTableModel a variable in your Statistics class.
Create a method in Statistics that interacts with the table model by
calling addRow() on the model.

JTable is not showing result after update?

I am creating a table at run time after fetching the result from the database. The flow of my application is like this.
Initializing a empty JScrollPane(); JScrollPane tableScroll = new JScrollPane();
Fetching result from the database;
Updating result to JTable and adding JTable to JScrollPane using following method:
Code:
private void setResultTable(Vector documents, Vector header) {
TableModel model = new DefaultTableModel(documents, header);
documentTable.setModel(model);
tableScroll.add(documentTable);
tableScroll.repaint();
}
my problem is that after calling setResultTable the result are not appearing in the table. Please help me with that. Thanks in advance !!!
You appear to be adding the JTable directly to the JScrollPane. If so this isn't correct and you'll want to change this so that you're actually adding the table to the scroll pane's viewport:
tableScroll.getViewport().add(documentTable);
There is no need to repaint the JScrollPane after doing this.
For example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class AddTableToScroll {
public static void main(String[] args) {
final JScrollPane sPane = new JScrollPane();
// Sorry Jeanette!!
sPane.setPreferredSize(new Dimension(200, 150));
JButton button = new JButton(new AbstractAction("Press Me!") {
public void actionPerformed(ActionEvent arg0) {
DefaultTableModel model = new DefaultTableModel(new Integer[][] {
{ 1, 2 }, { 3, 4 } }, new String[] { "A", "B" });
JTable table = new JTable(model);
sPane.getViewport().add(table);
}
});
JPanel panel = new JPanel();
panel.add(sPane);
panel.add(button);
JOptionPane.showMessageDialog(null, panel);
}
}
If this doesn't help, you'll want to also tell us exactly what happens, what you see, and if possible supply us with a small compilable runnable program that demonstrates your problem, an SSCCE

Categories

Resources