Column name not updating in JTable - java

I have a JTable for which I have made a table model. But on passing the column names to table model, it is not updating the column names. Can someone tell me why?
class MyTableModelTwo extends AbstractTableModel {
private Object[][] data;
private String[] columnNames = {"Name", "ID Number", "CGPA"};
public MyTableModelTwo(Object[][] data) {
this.data = data;
}
#Override
public int getRowCount() {
return data.length;
}
#Override
public int getColumnCount() {
return columnNames.length;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
return data[rowIndex][columnIndex];
}
#Override
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
#Override
public boolean isCellEditable(int rowIndes, int columnIndex) {
return false;
}
#Override
public void setValueAt(Object value, int rowIndex, int columnIndex) {
data[rowIndex][columnIndex] = value;
fireTableCellUpdated(rowIndex, columnIndex);
}
}
class MyTableTwo extends JPanel implements TableModelListener {
private JTable table;
private Object[][] data;
private JTextField t;
public MyTableTwo() {
data = new Object[3][3];
t = new JTextField();
for (int i = 0; i < noElements; i++) {
data[i][0] = "Kaushik";
data[i][1] = "2008A3";
data[i][2] = "7.79";
}
MyTableModelTwo m = new MyTableModelTwo(data);
table = new JTable(m);
}
#Override
public void tableChanged(TableModelEvent e) {
int row = table.getRowCount();
double sum = 0, d = 0;
for (int i = 0; i < row; i++) {
double c = (Double) table.getValueAt(i, 16);
sum += c;
}
t.setText("" + sum);
t.setHorizontalAlignment(JTextField.RIGHT);
}
}

You need to override getColumnName(int index) in your TableModel.
#Override
public String getColumnName(int index) {
return columnNames[index];
}

Related

show specific column in JTable with a predefined model

I have a JTable with 10 columns headers: "A","d","e","f","B","g","h","C","i","j".I want in first view JTable Show only "A","B","C" and I have two JButton when clicked on ViewAll Button all columns show and when clicked on hide Jtable show only three columns with "A","B","C" headers.how can do it?my GridTableModel is:
public abstract class GridTableModel<T> extends AbstractTableModel {
private static final long serialVersionUID = 4283080272635443348L;
private List<T> rows = new ArrayList<T>();
/**
* The property used to find real index of rows that currently are shown to user.
*/
private int offset;
public abstract String[] getColumnNames();
#Override
public String getColumnName(int column) {
return getColumnNames()[column];
}
#Override
public int getColumnCount() {
return getColumnNames().length;
}
#Override
public int getRowCount() {
return rows == null ? 0 : rows.size();
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
if (rows.size() > 0) {
return getValueAt(rows.get(rowIndex), rowIndex, columnIndex);
}
return null;
}
public void setData(List<T> results, int offset) {
this.rows = results;
this.offset = offset;
fireTableDataChanged();
}
public T get(int row) {
return rows.size() > 0 ? rows.get(row) : null;
}
public abstract Object getValueAt(T t, int rowIndex, int columnIndex);
public List<T> get(int[] rows) {
List<T> list = new ArrayList<T>();
for (int row : rows) {
list.add(this.rows.get(row));
}
return list;
}
public int getOffset() {
return offset;
}
public void setOffset(int offset) {
this.offset = offset;
}
public List<T> getRows() {
return rows;
}
#Override
public Class<?> getColumnClass(int columnIndex) {
if (1==1) {
return Object.class;
}
return getValueAt(0, columnIndex).getClass();
}
}

JTable ComboBox

For some reason this was removed.
This question is CLOSED and i won't be reading it as i have moved onwards and implemented more methods working. So no need putting snarky comments here, i won't read them.
Ok, so this might be quite the simple question, but here goes. I am setting up a JTable for editing and i want column 1 to have a comboBox editor. I looked up how to do it and followed the instructions which lead me to the code under, however it doesn't seem to actually update into the display. What am I misssing here? Thank you in advance.
//MainWindow class
public class MainWindow extends JFrame{
GridBagConstraints gbc;
JTable gridDisplay;
private AbstractTableModel tableModel;
JLabel statusBar;
MainWindow()
{
super("LayoutEditor");
setLayout(new BorderLayout());
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
gridDisplay = new JTable();
tableModel = new MyTableModel();
gridDisplay.setAutoCreateRowSorter(true);
gridDisplay.setColumnSelectionAllowed(true);
gridDisplay.setCellSelectionEnabled(true);
gridDisplay.setModel(tableModel);
TableColumn tc = gridDisplay.getColumnModel().getColumn(0);
JComboBox<String> cb = new JComboBox<String>();
cb.addItem("JLabel");
cb.addItem("JButton");
cb.addItem("JTextField");
cb.addItem("JTextArea");
cb.addItem("JCheckBox");
cb.addItem("JList");
cb.addItem("JComboBox");
cb.addItem("JSpinnerList");
cb.addItem("JSpinnerNumber");
cb.setSelectedIndex(0);
tc.setCellEditor(new DefaultCellEditor(cb));
MyDataModel temp= new MyDataModel();
MyTableModel table = (MyTableModel)gridDisplay.getModel();
table.append(temp);
JScrollPane gridScroll = new JScrollPane(gridDisplay);
mainPanel.add(toolBox, BorderLayout.NORTH);
mainPanel.add(gridScroll, BorderLayout.CENTER);
add(mb, BorderLayout.NORTH);
add(mainPanel, BorderLayout.CENTER);
setSize(1280,720);
setVisible(true);
}
]
//myTableModel class
public class MyTableModel extends AbstractTableModel {
ArrayList<MyDataModel> data;
String[] names;
MyTableModel()
{
names = new String[]{"Type","Variable name","Text","Row","Column","Rows","Columns","Fill","Anchor"};
data = new ArrayList<MyDataModel>();
}
#Override
public int getRowCount() {
return data.size();
}
#Override
public int getColumnCount() {
return names.length;
}
#Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
switch (columnIndex)
{
case 0:
data.get(rowIndex).setType(aValue.toString());
case 1:
data.get(rowIndex).setName(aValue.toString());
case 2:
data.get(rowIndex).setText(aValue.toString());
case 3:
data.get(rowIndex).setRow((int)aValue);
case 4:
data.get(rowIndex).setColumn((int)aValue);
case 5:
data.get(rowIndex).setRows((int)aValue);
case 6:
data.get(rowIndex).setColumns((int)aValue);
case 7:
data.get(rowIndex).setFill((int)aValue);
case 8:
data.get(rowIndex).setAnchor((int)aValue);
}
fireTableCellUpdated(rowIndex, columnIndex);
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
switch (columnIndex){
case 0:
return data.get(rowIndex).getType();
case 1:
return data.get(rowIndex).getName();
case 2:
return data.get(rowIndex).getText();
case 3:
return data.get(rowIndex).getRow();
case 4:
return data.get(rowIndex).getColumn();
case 5:
return data.get(rowIndex).getRows();
case 6:
return data.get(rowIndex).getColumns();
case 7:
return data.get(rowIndex).getFill();
case 8:
return data.get(rowIndex).getAnchor();
}
return null;
}
public void append(MyDataModel item)
{
data.add(item);
}
#Override
public String getColumnName(int column) {
return names[column];
}
}
//MyDataModel Class
public class MyDataModel {
String type, name, text;
int row, column, rows, columns, fill, anchor;
MyDataModel()
{
type = new String("");
name = new String("");
text = new String("");
row = 0;
column = 0;
rows = 0;
columns = 0;
fill = 0;
anchor = 0;
}
public MyDataModel(MyDataModel test) {
type = test.getType();
name = test.getName();
text = test.getText();
row = test.getRow();
column = test.getColumn();
rows = test.getRows();
columns = test.getColumns();
fill = test.getFill();
anchor = test.getAnchor();
}
public int getAnchor() {
return anchor;
}
public void setAnchor(int anchor) {
this.anchor = anchor;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public int getRow() {
return row;
}
public void setRow(int row) {
this.row = row;
}
public int getColumn() {
return column;
}
public void setColumn(int column) {
this.column = column;
}
public int getRows() {
return rows;
}
public void setRows(int rows) {
this.rows = rows;
}
public int getColumns() {
return columns;
}
public void setColumns(int columns) {
this.columns = columns;
}
public int getFill() {
return fill;
}
public void setFill(int fill) {
this.fill = fill;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
it doesn't seem to actually update into the display.
The value you select from the combo box is not being saved in the TableModel.
Your TableModel needs to implement the setValueAt(...) method.
See the section from the Swing tutorial on Create a Table Model for a simple implementation. It also shows you what fireXXX(...) method to invoke so the table is notified of the change in data.
You're missing a bit from your model including setValueAt(...), isCellEditable(...), and you forgot to call fireTableRowsInserted(...) inside of your append method.
e.g.,
public void append(MyDataModel item) {
data.add(item);
// !! don't forget this!!
int firstRow = getRowCount() - 1;
int lastRow = firstRow;
fireTableRowsInserted(firstRow, lastRow);
}
#Override
public String getColumnName(int column) {
return names[column];
}
#Override //!!
public boolean isCellEditable(int rowIndex, int columnIndex) {
return columnIndex == 0; // allow editing of first column
}
#Override //!!
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
if (columnIndex == 0) {
MyDataModel row = data.get(rowIndex);
row.setType(aValue.toString());
fireTableCellUpdated(rowIndex, columnIndex);
return;
}
super.setValueAt(aValue, rowIndex, columnIndex);
}
You will want to re-read the JTable tutorial because you're skipping a lot of key concepts.
And I forgot -- you also need to override public boolean isCellEditable(int row, int col) and have it return true, at least for the JComboBox column, else you'll never see combo boxes since it is an editor.

JTable Rows Not Rendered in Expected Colors

I have a jtable , a customtablemodel and a customcellrenderer with the NetBeans IDE.
I want to have different colors for different rows. But anytime I run the application ,
the rows are not painted as expected.
The code snippets are provided below.
This code is from the jtable :
duesTable = new javax.swing.JTable();
duesTable.setModel(duestableModel);
TableColumn tcol = duesTable.getColumnModel().getColumn(2);
tcol.setCellRenderer(new CustomTableCellRenderer2());
duesTable.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
this code is from the TableCellRenderer
public class CustomTableCellRenderer2 extends DefaultTableCellRenderer{
#Override
public Component getTableCellRendererComponent (JTable table,
Object obj, boolean isSelected, boolean hasFocus, int row, int column) {
Component cell = super.getTableCellRendererComponent(
table, obj, isSelected, hasFocus, row, column);
if (isSelected) {
cell.setBackground(Color.green);
}
else {
if (row % 2 == 0) {
cell.setBackground(Color.green);
}
else {
cell.setBackground(Color.lightGray);
}
}
return cell;
}
}
This is from the Table Model.
public class DuesTableModel extends AbstractTableModel implements TableModelListener {
private List<List<Object>> dataList = new ArrayList<>();
private String[] header = { "ID"," PAYMENT YEAR" , "AMOUNT"}; // Payment year is a date
datatype
private int minRowCount = 5;
public DuesTableModel()
{ super(); }
public List<List<Object>> getDataList() {
return dataList;
}
public void setDataList(List<List<Object>> dataList) {
this.dataList = dataList;
fireTableDataChanged();
fireTableStructureChanged();
}
#Override
public int getRowCount() {
return Math.max(minRowCount, dataList.size());
}
#Override
public int getColumnCount() {
return header.length;
}
public void setHeader(String[] header) {
this.header = header;
}
public String[] getHeader() {
return header;
}
#Override
public void setValueAt(Object value, int row, int col)
{
int x = 0;
for(List<Object> l : dataList)
{
if(x == row)
{ l.set(col, value);}
x++;
}
fireTableCellUpdated(row,col);
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
Object value = null;
if(rowIndex < dataList.size())
{value = dataList.get(rowIndex).get(columnIndex);}
return value;
}
#Override
public String getColumnName(int col) {
return header[col];
}
#Override
public Class<?> getColumnClass(int column)
{
switch (column) {
case 0:
return Integer.class;
case 1:
return Date.class;
case 2:
return Double.class;
default:
return String.class;
}
}
#Override
public boolean isCellEditable(int row, int col) {
return true; //col != 1;
}
#Override
public void tableChanged(TableModelEvent e) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
Any suggestion to get the desired result.

Refresh Jtable Content

The purpose of this code is, fill the table with random numbers when something is write in the cell[0,1];
the problem is that the table do not automatically refresh itself.
The table refresh the content only when i move a border or i click on the cells.
import javax.swing.table.TableModel;
public abstract class AbstractTableData implements TableModel{
public static AbstractTableData getTabellaDati(){
throw new UnsupportedOperationException("");
};
#Override
abstract public boolean isCellEditable(int rowIndex, int columnIndex);
}
/---------------------------------------------------/
import java.util.Random;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableModel;
public class TableData extends AbstractTableData{
public static final int N_C = 10;
public static final int N_R = 10;
public String[] heading;
public String[][] data;
public TableData(String[] h, String[][] data) {
this.heading = h;
this.data = data;
}
#Override
public int getRowCount() {
return heading.length;
}
#Override
public int getColumnCount() {
return data.length;
}
#Override
public String getColumnName(int columnIndex) {
return heading[columnIndex];
}
#Override
public Class<?> getColumnClass(int columnIndex) {
return "".getClass();
}
#Override
public boolean isCellEditable(int rowIndex, int columnsIndex) {
if (rowIndex == 0) {
if (columnsIndex == 0) {
return false;
} else {
return true;
}
} else {
return false;
}
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
return data[rowIndex][columnIndex];
}
#Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
data[rowIndex][columnIndex] = (String)aValue;
fireTableUpadate(rowIndex, columnIndex);
}
#Override
public void addTableModelListener(TableModelListener l) {
}
#Override
public void removeTableModelListener(TableModelListener l) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
private void fireTableUpadate(int rowIndex, int columnIndex)
{
Random ran =new Random();
for(int i=1;i<N_R;i++)
for(int j=0;j<N_R;j++)
data[i][j]=""+ran.nextInt();
}
}
/------------------------------------------/
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTable;
public class Test {
public static void main(String[] args) {
String[] head = new String[TableData.N_C];
String[][] data = new String[TableData.N_R][TableData.N_C];
for (int i = 0; i < TableData.N_C; i++) {
head[i] = "" + i;
}
for (int i = 0; i < TableData.N_R; i++) {
for (int j = 0; j < TableData.N_C; j++) {
data[i][j] = "";
}
}
data[0][0]="->";
JTable table = new JTable(data, head);
table.setModel(new TableData(head,data));
JPanel panel = new JPanel();
JFrame frame = new JFrame();
frame.add(panel.add(table));
frame.setSize(1000, 380);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
AbstractTableData has to remain the same.
I hope someone will find what's wrong!

Converting selected items on a Table model to an object

I have Components I have created that are being put into a table model with two columns as below.
if (!newAcList.isEmpty()) {
for (Acronym acc : newAcList) {
tableModel.addRow(new String[]{acc.getName(), acc.getDefinition()});
}
}
What I need is when the user selects an item on the table model it converts the item back to my Acronym Object. I am using a Listselectionevent Listener.
Here is valueChanged selection event``
#Override
public void valueChanged(ListSelectionEvent e) {
String selectedAcData = null;
String selectDefData = null;
int[] selectedRow = accTable.getSelectedRows();
int[] selectedColumns = accTable.getSelectedColumns();
for (int i = 0; i < selectedRow.length; i++) {
// for (int j = 0; j < selectedColumns.length; j++) {
selectedAcData = (String) accTable.getValueAt(selectedRow[i], 0);
}
}
You might want to create a class that implements the TableModel interface for the acronyms. It might be called AcronymTableModel and is backed by a List<Acronym> list of Acronyms. Then give this model to your table.
The call to accTable.getValueAt(selectedRow[i], 0); in your valueChanged method will then return an instance of an Acronym.
Here's a quick example.
public class Example {
public static void main(String [] a) {
JFrame f = new JFrame();
JPanel p = new JPanel();
List<Acronym> acronyms = new ArrayList<Acronym>();
acronyms.add(new Acronym("FBI", "Federal Bureau of Investigation"));
acronyms.add(new Acronym("CIA", "Central Intelligence Agency"));
final TableModel tModel = new AcronymTableModel(acronyms);
JTable t = new JTable(tModel);
t.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
Acronym a = (Acronym)tModel.getValueAt(e.getFirstIndex(), 0);
System.out.println(a.acronym + ": " + a.definition);
}});
p.add(t);
f.getContentPane().add(p);
f.pack();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.setVisible(true);
}
}
class Acronym {
String acronym;
String definition;
public Acronym(String a, String d) {
acronym = a;
definition = d;
}
}
class AcronymTableModel implements TableModel {
private List<Acronym> acronyms;
public AcronymTableModel(List<Acronym> acs) {
this.acronyms = new ArrayList<Acronym>(acs);
}
#Override
public int getRowCount() {
return this.acronyms.size();
}
#Override
public int getColumnCount() {
return 2;
}
#Override
public String getColumnName(int columnIndex) {
switch(columnIndex) {
case 0:
return "Acronym";
case 1:
return "Definition";
}
return null;
}
#Override
public Class<?> getColumnClass(int columnIndex) {
return String.class; // Since both columns are simply
}
#Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return false;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
return acronyms.get(rowIndex);
}
#Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
}
#Override
public void addTableModelListener(TableModelListener l) {
}
#Override
public void removeTableModelListener(TableModelListener l) {
}
}
The Java tutorials are always good and have good examples.
http://docs.oracle.com/javase/tutorial/uiswing/events/listselectionlistener.html

Categories