The JTable.updateUI() doesn't refresh my table - java

I am trying to refresh my table panel when I click the LOAD button. The method replaceText() will be called the LOAD button in GUI is clicked. A new columnNames list and display content will be sent to update my tableModel which extends AbstractTableModel. Then table.updateUI() is called to refresh the table.
public class Table {
private JPanel panel;
private TableModel model;
private JTable table;
private JScrollPane scrollPane;
public Table(){
this.panel = new JPanel();
this.model = new TableModel();
this.table = new JTable(model);
this.scrollPane = new JScrollPane(table);
}
public void replaceText(ArrayList<String> names, String[][] content){
model.update(names, content);
table.updateUI();
}
public JPanel build(){
panel.setSize(1000, 300);
panel.setLayout(new BorderLayout());
panel.add(scrollPane, BorderLayout.CENTER);
panel.setVisible(true);
return panel;
}
}
And here is the code in my tableModel:
public class TableModel extends AbstractTableModel {
String[] colNames = new String[] {};
String[][] content = new String[][] {};
#Override
public int getRowCount() {
return content.length;
}
#Override
public int getColumnCount() {
return colNames.length;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
return content[rowIndex][columnIndex];
}
public String getColumnName(int columIndex){
return colNames[columIndex];
}
public void update(ArrayList<String> names, String[][] content){
this.colNames = names.toArray(new String[0]);
this.content = content;
}
}

public class TableModel extends AbstractTableModel {
There is an interface called TableModel. Don't name the class the same as the interface. It is confusing.
table.updateUI();
You should NOT invoke updateUI(). That method is only used internally by Swing when you change the LAF. Changing the data is not changing the LAF.
It is the responsibility of the "model" to update the "view" when the data of the model is changed.
public void update(ArrayList<String> names, String[][] content){
this.colNames = names.toArray(new String[0]);
this.content = content;
}
Your update(…) method does NOT notify the view that the data has changed. This would be done by invoking the:
fireTableStructureChanged(…);
method of the AbstractTableModel in your update(…) method.
However, I see no reason to create a custom TableModel. I would suggest you just use the DefaultTableModel. It has a method setDataVector(…) that allows you to reset the data in the model.

Related

empty TableModel after instantiating

Newbie seeking help please :-)
I am working on a little project to get familiar with Java desktop development and Database connectivity.
Attached code gives me an empty TableModel after instantiating therefore no data displayed in the JFrame.
Test class is instantiated from the menue of the main window with Test.showFrame();.
package ...
import ...
public class Test extends JPanel {
public Test() {
initializePanel();
}
private void initializePanel() {
// Creates an instance of TableModel
CategoryTableModel tableModel = new CategoryTableModel();
System.out.println(tableModel.getRowCount());
// Creates an instance of JTable with a TableModel
// as the constructor parameters.
JTable table = new JTable(tableModel);
table.setFillsViewportHeight(true);
JScrollPane scrollPane = new JScrollPane(table);
this.setPreferredSize(new Dimension(500, 200));
this.setLayout(new BorderLayout());
this.add(scrollPane, BorderLayout.CENTER);
}
public static void showFrame() {
JPanel panel = new Test();
panel.setOpaque(true);
JFrame frame = new JFrame("test");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setContentPane(panel);
frame.pack();
frame.setVisible(true);
}
class CategoryTableModel extends AbstractTableModel {
private List<Category> all = null;
private Iterator<Category> iterator = null;
private int tableRowCount;
private TableModel tableModel;
public CategoryTableModel(){
Vector tableData = new Vector();
// TableModel's column names
Vector<String> tableHeaders = new Vector<String>();
tableHeaders.add("Category");
// Database call
all = new ReadCategory().allCategories();
// TableModel's data
for(Object o : all) {
Vector<Object> row = new Vector<Object>();
all.forEach((n) -> row.add(new Category().getName()));
tableData.add(row);
System.out.println("row added");
}
tableRowCount = tableData.size();
tableModel = new DefaultTableModel(tableData, tableHeaders);
System.out.println(tableModel.getRowCount());
}
#Override
public int getRowCount() {
return 0;
}
#Override
public int getColumnCount() {
return 0;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
return null;
}
}
}
Database call is fetching data via Hibernate and stores data in a .
Thanks for help.
In its most basic form a table model for a JTable defines the columns, the mapping of object to column and holds the data for the JTable to call upon. If we take your current table model and cut it down to fit this basic requirement we get the following.
import java.util.ArrayList;
import java.util.List;
import javax.swing.table.AbstractTableModel;
public class CategoryTableModel extends AbstractTableModel {
private final List<Category> tableData = new ArrayList<>();
public void add(Category cat) {
tableData.add(cat);
fireTableDataChanged();
}
#Override
public String getColumnName(int column) {
String result = "";
if (column == 0) {
result = "Category Name";
}
return result;
}
#Override
public int getRowCount() {
return tableData.size();
}
#Override
public int getColumnCount() {
return 1;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
if (columnIndex == 0) {
return tableData.get(rowIndex).getName();
}
return null;
}
}
Notice that we do not define any data in the model itself. All we define is some storage for the data and the column name of the single column that we require.
I have added an add() method that allows you to add data to the model (you may wish to define remove etc. yourself). When you add or remove data from the model you must always let the JTable know that the data has changed by calling fireTableDataChanged() so that the table can redraw itself.
To use this table model you will need to do
CategoryTableModel model = new CategoryTableModel();
model.add(new Category());
JTable table = new JTable(model);
You can replace the model.add() with a loop that iterates over your data and adds it to the model.

How to add a button inside a table cell in java netbeans? (I am using the drag and drop method.)

I am trying to add a button inside a table cell. I am using the drag and drop method of netbeans since I know nothing about coding and will appreciate if you can teach me to code it. Thanks!
If you are using drag&drop in netbean for swing,
I highly advise you to touch the fundamental of swings , get your hands dirty so that you will know what is going on and how does the code work.
let me run through how you can achieve this. it will consist of 3 classes so that you will have a better understanding on what is going on and it practices oop too but of cause you can modify it to your preferred design pattern.
_main.java
public class _main extends JFrame{
private static final long serialVersionUID = 1L;
// Create new JFrame
_main(){
new JFrame("Main");
setLayout(new BorderLayout());
setSize(500,300);
add(new JLabel("Table Example ", SwingUtilities.CENTER) , BorderLayout.PAGE_START);
// ---------------- Call the method you have created in tableView.java ------------
add(new JScrollPane(new tableView(this).sampleTable()), BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args){
//Run Program
new _main();
}
}
tableView.java
public class tableView {
JFrame frame = new JFrame();
public tableView(JFrame frame) {
this.frame = frame;
}
//Create columnTitle & Table Model
String[] columnTitle = { "Data 1", "Data 2", "Data 3", "Buttons " };
DefaultTableModel model = new DefaultTableModel(columnTitle, 0);
public JTable sampleTable(){
JTable _dataTable = new JTable(model) {
#Override
public void updateUI() {
super.updateUI();
setRowHeight(34);
setAutoCreateRowSorter(true);
//------------ Placing button at your desired column ------------
TableColumn column;
column = getColumnModel().getColumn(3);
column.setCellRenderer(new tableModel(frame).new viewRenderer());
column.setCellEditor(new tableModel(frame).new ButtonsEditorView(this));
}
};
DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
centerRenderer.setHorizontalAlignment(JLabel.CENTER);
//-------- Adding data to your table row , use for loop for multiple data ---------
model.addRow(new Object[]{"1","2","3"});
return _dataTable;
}
}
tableModel.java
public class tableModel extends tableView{
public tableModel(JFrame frame) {
super(frame);
}
class viewButton extends JPanel {
public JButton viewbtnp = new JButton("View");
protected viewButton() {
setOpaque(true);
setFocusable(false);
add(viewbtnp);
}
}
class viewRenderer implements TableCellRenderer {
private final viewButton panel = new viewButton() {
#Override
public void updateUI() {
super.updateUI();
setName("Table.cellRenderer");
}
};
#Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
int row, int column) {
panel.setBackground(isSelected ? table.getSelectionBackground() : table.getBackground());
return panel;
}
}
class ViewAction extends AbstractAction {
private final JTable table;
protected ViewAction(JTable table) {
super("view");
this.table = table;
}
#Override
public void actionPerformed(ActionEvent e) {
//--------------------------- Create your own function on what you want the button to do when button is clicked -------------
System.out.println("Clicked ");
}
}
class ButtonsEditorView extends AbstractCellEditor implements TableCellEditor {
protected final viewButton panel = new viewButton();
protected final JTable table;
protected ButtonsEditorView(JTable table) {
super();
this.table = table;
panel.viewbtnp.setAction(new ViewAction(table));
}
#Override
public Component getTableCellEditorComponent(JTable tbl, Object value, boolean isSelected, int row,
int column) {
panel.setBackground(tbl.getSelectionBackground());
return panel;
}
#Override
public Object getCellEditorValue() {
return "";
}
}
}
Output
Hope it helps.
Cheers

How do I insert new row into a JTable using a custom table model?

I'm working on a small project that involves JTable which requires the user to click a button and add a row to the table (I have named the button as addrow). I have used a custom table model (Mytablemodel) which extends Default table model.
My table is first made up of five rows and 4 columns where afterwards user can click the addrow button to add more rows
Everything in my code works fine except the addrow button which does nothing. I will appreciate any help.
public class AddingNewRows extends JFrame {
JTable mytable;
JButton addrow;
String[] columns={"Admission number","Name","School","Year"};
TableColumn tc;
int defaultrows=5;
int rows=new Mytablemodel().getRowCount(),columnscount=new Mytablemodel().getColumnCount();
List data=new ArrayList();
Mytablemodel mytbm;
//
public AddingNewRows(){
super("adding rows");
for(int initialrows=0; initialrows<5; initialrows++){
String[] items={"1","2","3","4"};
data.add(items);
}
mytbm=new Mytablemodel();
mytable=new JTable(mytbm);
JScrollPane scroll=new JScrollPane(mytable);
addrow=new JButton("ADD ROW");
//
JPanel buttonpanel=new JPanel();
buttonpanel.setLayout(new BoxLayout(buttonpanel,BoxLayout.X_AXIS));
buttonpanel.setAlignmentX(Component.RIGHT_ALIGNMENT);
buttonpanel.add(addrow);
//
add(scroll,BorderLayout.CENTER);
add(buttonpanel,BorderLayout.SOUTH);
addrow.addActionListener(new Myactions());
}
public class Mytablemodel extends DefaultTableModel{
#Override
public String getColumnName(int column) {
return columns[column];
}
#Override
public Object getValueAt(int row, int col){
return ((String[])data.get(row))[col];
}
#Override
public boolean isCellEditable(int row, int col){
return true;
}
#Override
public void setValueAt(Object value,int row, int col){
((Object[])data.get(row))[col]=value;
fireTableCellUpdated(row,col);
}
#Override
public Class getColumnClass(int column){
return getValueAt(0,column).getClass();
}
#Override
public int getColumnCount(){
return columns.length;
}
#Override
public int getRowCount(){
return increaserows;
}
#Override
public void addRow(Object[] mynewdata){
int rownum=data.size();
System.out.println(rownum);
data.add(madata);
fireTableRowsInserted(rownum,rownum);
}
}
//
private class Myactions implements ActionListener{
#Override
public void actionPerformed(ActionEvent event){
if(event.getSource()==addrow){
Object[]newdata={"","","",""};
mytbm.addRow(newdata);
}
}
}
public static void main(String[] args) {
AddingNewRows frame=new AddingNewRows();
frame.setVisible(true);
frame.setSize(400,400);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
}
}
Some notes about your code:
You never should call any of the fireXxx() methods explicitely from the
outside. Those are intended to be called internally by
AbstractTableModel subclasses when needed. Note: IMHO those should
be protected and not public, to avoid use them incorrectly. But for
some reason they made them public.
Your addrow button seems to create a new table model that is not
attached to any JTable so it makes no sense. Your table model should
provide an addRow(...) method in order to add a new row to it. Most
likely you will have to enlarge the two-dimensions array that is the
table model's underlyinig data structure any time a row is added.
As #AndrewThompson already suggested, DefaultTableModel seems a
good match to do what your table model does.
Check rows and columnscount properties initialization. It doesn't
seem right to me.
On the other hand, you say in a comment:
I'm having trouble understanding the fireTableRowsInserted(int,int) method. the parameters themself and
where or when to call the method
This method should be called within the addRow(...) that I've suggested you to create in the second point. This method should enlarge the data structure and notify the TableModelListeners that a new row/s has/have been inserted. The parameters are the first and last indexes respectively. Tipically when you append a new single row to the end of the table model, then both first and last indexes are the same and the new size - 1 of the underlying data structure. Of course, several rows can be inserted and not necessarily at the end of the table model, so you have to figure out the appropriate indexes. See the example shown here which uses a List of custom objects as data structure.
According to your question,You want to add new rows every time the user clicks the addrow button.
Achieve your objective by using DefaultTableModel without creating your own or overriding addrow method.
in my example below,parameters in the DefaultTableModel constructor represents the initial rows(5) and columns(4) that the table will have where after execution, the user can add more rows by clicking the addrow button.
public class AddingNewRows extends JFrame {
DefaultTableModel def;
JTable mytable;
JButton addrow;
//
public AddingNewRows(){
super("adding rows");
def=new DefaultTableModel(5,4);
mytable=new JTable(def);
JScrollPane scroll=new JScrollPane(mytable);
addrow=new JButton("ADD ROW");
//
JPanel buttonpanel=new JPanel();
buttonpanel.setLayout(new BoxLayout(buttonpanel,BoxLayout.X_AXIS));
buttonpanel.add(addrow);
//
add(scroll,BorderLayout.CENTER);
add(buttonpanel,BorderLayout.SOUTH);
addrow.addActionListener(new Myactions());
}
private class Myactions implements ActionListener{
#Override
public void actionPerformed(ActionEvent event){
if(event.getSource()==addrow){
Object[]newdata={"","","",""};
def.addRow(newdata);
}
}
}
public static void main(String[] args) {
AddingNewRows frame=new AddingNewRows();
frame.setVisible(true);
frame.setSize(400,400);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
}
}

JComboBox custom editor JTable

I want to add Jtable to JComboBox Editor, so when i select the ComboBox the JTable show up.
I can't use table.removeActionListener() and table.addActionListener(). we new functions
table.addAncestorListener( addAncestorListener listener) and
table.removeAncestorListener(addAncestorListener listener)
her is my code so far,
public class CustomComboEditor implements ComboBoxEditor {
private JTable table ;
public CustomComboEditor() {
table = new JTable();
}
#Override
public void addActionListener(ActionListener l) {
// there is no addActionListener(l) for table
}
#Override
public Component getEditorComponent() {
return table ;
}
#Override
public Object getItem() {
return table.getValueAt(table.getSelectedRow(), table.getSelectedColumn());
}
#Override
public void removeActionListener(ActionListener l) {
// there is no removeActionListener(l);for table
}
#Override
public void selectAll() {
table.selectAll();
}
#Override
public void setItem(Object anObject) {
return ;
}
}
her is an image illustrates what i want exactly
combobox table editor http://im47.gulfup.com/ECk9HK.png
While it may be technically possible to use a JTable as a ComboBoxEditor, the result may be unwieldy. Instead, add the desired instances of your TableModel to the combo's ComboBoxModel and use setModel() to display the selected model in an adjacent JTable. Summarized below, a complete example is shown here.
DefaultComboBoxModel dcbm = new DefaultComboBoxModel();
private JComboBox combo = new JComboBox(dcvm);
…
for (int i = 0; i < N; i++) {
…
TableModel model = new YourTableModelModel(name);
dcbm.addElement(model);
}
…
combo.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
TableModel model = (TableModel) combo.getSelectedItem();
table.setModel(model);
}
});

synchronize view of two JTable

I have two JTables one in main viewport and one in footer viewport, using JideScrollPane.
the problem is when the main JTable's view is customized, the footer JTable remains the
same, is there any way to synchronize their view?
thanks.
EDIT:
Here's a demo that will synch up the resizing of two tables that have similar columns. The idea is:
Create a custom TableColumnModelListener for each table's column model.
Upon resize, sync up the column widths. You'll have to disable the other listener temporarily, while this is happening.
For moving of columns, implement that logic in columnMoved(...) [left as an exercise]
This shows two-way synching:
import java.awt.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
public class JTableResizeColumnsDemo implements Runnable
{
JTable table1, table2;
TableColumnModelListener columnListener1, columnListener2;
Map<JTable, TableColumnModelListener> map;
public static void main(String[] args)
{
SwingUtilities.invokeLater(new JTableResizeColumnsDemo());
}
public void run()
{
Vector<String> names = new Vector<String>();
names.add("One");
names.add("Two");
names.add("Three");
table1 = new JTable(null, names);
table2 = new JTable(null, names);
columnListener1 = new ColumnChangeListener(table1, table2);
columnListener2 = new ColumnChangeListener(table2, table1);
table1.getColumnModel().addColumnModelListener(columnListener1);
table2.getColumnModel().addColumnModelListener(columnListener2);
map = new HashMap<JTable, TableColumnModelListener>();
map.put(table1, columnListener1);
map.put(table2, columnListener2);
JPanel p = new JPanel(new GridLayout(2,1));
p.add(new JScrollPane(table1));
p.add(new JScrollPane(table2));
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(p);
frame.setSize(300, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
class ColumnChangeListener implements TableColumnModelListener
{
JTable sourceTable;
JTable targetTable;
public ColumnChangeListener(JTable source, JTable target)
{
this.sourceTable = source;
this.targetTable = target;
}
public void columnAdded(TableColumnModelEvent e) {}
public void columnSelectionChanged(ListSelectionEvent e) {}
public void columnRemoved(TableColumnModelEvent e) {}
public void columnMoved(TableColumnModelEvent e) {}
public void columnMarginChanged(ChangeEvent e)
{
TableColumnModel sourceModel = sourceTable.getColumnModel();
TableColumnModel targetModel = targetTable.getColumnModel();
TableColumnModelListener listener = map.get(targetTable);
targetModel.removeColumnModelListener(listener);
for (int i = 0; i < sourceModel.getColumnCount(); i++)
{
targetModel.getColumn(i).setPreferredWidth(sourceModel.getColumn(i).getWidth());
}
targetModel.addColumnModelListener(listener);
}
}
}
You can apply an Observer pattern: the first JTable observes the second and vice versa. Then you add listners to both tables so that, when one is "customized", the other is notified. Basically, "being notified" consists in a method invocation that causes the update of the JTable.
In order to do that, you have two options:
You define a class Observer with a "register" method and a
"notify" method. When creating a JTable, you register it with the
Observer. Then, the listener you create and associate to each JTable
invoke the "notify" method of the observer, which informs all other
registered JTables of the change
You define a sort of "callback method" notify in the class that contains and declares the JTable. This "notify" method is invoked within the listner and updates the correct JTable. You can also create two methods: one for updating one JTable and one for the other JTable
Usually this is done by using the same model for different ui components. Sadly the JTable contains a bug that will cause problems when sharing the TableColumnModel.
But you can work around it using this JTable
class ShareableColumnModelTable extends JTable {
/**
* Fixes http://bugs.java.com/bugdatabase/view_bug.do?bug_id=4816146 and
* more...
*
*/
#Override
public void columnMarginChanged(ChangeEvent e) {
if (isEditing()) {
removeEditor();
}
TableColumn resizingColumn = null;
if (tableHeader != null) {
resizingColumn = tableHeader.getResizingColumn();
}
if (resizingColumn != null) {
if (autoResizeMode == AUTO_RESIZE_OFF) {
resizingColumn.setPreferredWidth(resizingColumn.getWidth());
} else { // this else block is missing in jdk1.4 as compared to
// 1.3
TableColumnModel columnModel = getColumnModel();
/**
* Temporarily disconnects this column listener to prevent
* stackoverflows if the column model is shared between
* multiple JTables.
*/
columnModel.removeColumnModelListener(this);
try {
doLayout();
} finally {
columnModel.addColumnModelListener(this);
}
repaint();
return;
}
}
resizeAndRepaint();
}
}
With the ShareableColumnModelTableshowed above you can share one column model bettween multiple tables.
public static void main(String[] args) {
JFrame frame = new JFrame("Column Sync");
Container contentPane = frame.getContentPane();
JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
splitPane.setResizeWeight(0.5d);
contentPane.add(splitPane);
JTable table1 = new ShareableColumnModelTable();
JTable table2 = new ShareableColumnModelTable();
TableColumnModel tableColumnModel = createTableColumnModel();
table1.setModel(createTableModel1());
table2.setModel(createTableModel2());
table1.setColumnModel(tableColumnModel);
table2.setColumnModel(tableColumnModel);
splitPane.setLeftComponent(new JScrollPane(table1));
splitPane.setRightComponent(new JScrollPane(table2));
showFrame(frame);
}
private static TableColumnModel createTableColumnModel() {
TableColumnModel tableColumnModel = new DefaultTableColumnModel();
TableColumn column1 = new TableColumn(0);
column1.setHeaderValue("1. column");
tableColumnModel.addColumn(column1);
TableColumn column2 = new TableColumn(1);
column2.setHeaderValue("2. column");
tableColumnModel.addColumn(column2);
return tableColumnModel;
}
private static TableModel createTableModel1() {
DefaultTableModel tableModel = new DefaultTableModel();
tableModel.setColumnCount(2);
tableModel.addRow(new Object[] { "a", "b" });
return tableModel;
}
private static TableModel createTableModel2() {
DefaultTableModel tableModel = new DefaultTableModel();
tableModel.setColumnCount(2);
tableModel.addRow(new Object[] { "c", "d" });
return tableModel;
}
private static void showFrame(JFrame frame) {
frame.setSize(240, 400);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setVisible(true);
}

Categories