I have a table with two values: A and B
Is it possible to get A as int using getSelectedRow()?
At this moment I got this, it cannot find symbol for variable A
DefaultTableModel tm = (DefaultTableModel)jTabela.getModel();
int A = Integer.parseInt( tm.getValueAt(jTabela.A, getSelectedRow()).toString() );
You're putting the row number into the wrong parameter. Per the JTable API the getValueAt(...) method takes two int parameters, the first of which is the row index and the second is the column index. So you'll want something like:
DefaultTableModel tm = (DefaultTableModel)jTabela.getModel();
int row = tm.getSelectedRow();
if (row == -1) {
return;
}
Object value = jTabela.getValueAt(row, whateverYourColumnIs);
int intValue = value != null ? Integer.parseInt(value.toString()) : 0;
For example:
import java.awt.BorderLayout;
import java.util.Vector;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
#SuppressWarnings("serial")
public class TableExample extends JPanel {
private static final String[] COLUMNS = {"Name", "Value"};
private DefaultTableModel model = new DefaultTableModel(COLUMNS, 0) {
public java.lang.Class<?> getColumnClass(int columnIndex) {
Object value = getValueAt(0, columnIndex);
if (value == null) {
return super.getColumnClass(columnIndex);
} else {
return value.getClass();
}
};
};
private JTable table = new JTable(model);
public TableExample() {
for (int i = 0; i < 10; i++) {
String name = "Row " + (i + 1);
int value = (i + 1) * 10;
Vector<Object> row = new Vector<>();
row.add(name);
row.add(value);
model.addRow(row);
}
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting()) {
return;
}
int row = table.getSelectedRow();
if (row == -1) {
return;
}
Object value = table.getValueAt(row, 1); // numbers are in row 1
if (value != null) {
System.out.println("Selected value: " + value);
int intValue = Integer.parseInt(value.toString());
// can use value here
}
}
});
setLayout(new BorderLayout());
add(new JScrollPane(table));
}
private static void createAndShowGui() {
JFrame frame = new JFrame("Table Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new TableExample());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Related
I'm trying to create a dynamic JTable in Java Swing where users can add/delete rows and columns as they want. Everything is good, except for deleting the column. I've been at this for hours now and I can't figure out how to completely erase a column and its values.
There are removeColumn(int) methods in the classes, but they only hide the column from view. I've also searched and found this answer, but when I try to create the CustomTableModel class and extend DefaultTableModel, I just get a ClassCastException.
Adding a column
Determine the new index of the column (how you do this is up to you)
Determine the new values for each row/column - you could also just as easily set the values to null to start with
Update the row data in the model
Update the column data in the model (ie columnCount and columnName)
Trigger a TableModelEvent.HEADER_ROW event so that the JTable updates itself with the new data
Removing a column
Determine the column index to be removed
Remove the column data for each row
Update the column data in the model (ie columnCount and columnName)
Trigger a TableModelEvent.HEADER_ROW event so that the JTable updates itself with the new data
Runnable example
This is a basic example of the concept. Personally I prefer to manage my data via POJOs (which is here the idea of "hiding columns" would be more practical, but that might not always be possible
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private MutableTableModel model;
private JTable table;
public TestPane() {
setLayout(new BorderLayout());
JButton addColumnButton = new JButton("Add column");
JButton removeColumnButton = new JButton("Remove column");
addColumnButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
List<Object> rows = new ArrayList<>(100);
for (int row = 0; row < 100; row++) {
rows.add(randomString());
}
String columnName = JOptionPane.showInputDialog(TestPane.this, "Column name");
if (columnName == null || columnName.isBlank()) {
columnName = randomString();
}
int columnIndex = table.getSelectedColumn();
if (columnIndex < 0) {
model.addColumn(columnName, rows);
} else {
model.addColumn(columnName, rows, columnIndex + 1);
}
}
});
removeColumnButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int columnIndex = table.getSelectedColumn();
if (columnIndex < 0) {
JOptionPane.showMessageDialog(TestPane.this, "Now column selected");
} else {
model.removeColumn(columnIndex);
}
}
});
JPanel actionPanels = new JPanel(new GridBagLayout());
actionPanels.add(addColumnButton);
actionPanels.add(removeColumnButton);
add(actionPanels, BorderLayout.SOUTH);
String[] columnNames = new String[]{"One", "Two", "Three", "Four", "Five"};
List<List<Object>> rows = new ArrayList<>(100);
for (int row = 0; row < 100; row++) {
List<Object> rowData = new ArrayList<>(columnNames.length);
for (int col = 0; col < columnNames.length; col++) {
rowData.add(randomString());
}
rows.add(rowData);
}
model = new MutableTableModel(Arrays.asList(columnNames), rows);
table = new JTable(model);
add(new JScrollPane(table));
}
private Random random = new Random();
protected String randomString() {
int leftLimit = 48; // numeral '0'
int rightLimit = 122; // letter 'z'
int targetStringLength = 10;
String generatedString = random.ints(leftLimit, rightLimit + 1)
.filter(i -> (i <= 57 || i >= 65) && (i <= 90 || i >= 97))
.limit(targetStringLength)
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
return generatedString;
}
}
public class MutableTableModel extends AbstractTableModel {
private ArrayList<List<Object>> rows = new ArrayList<>(32);
private ArrayList<String> columnNames = new ArrayList<>(8);
public MutableTableModel() {
}
public MutableTableModel(List<String> columnNames, List<List<Object>> rows) {
this.columnNames = new ArrayList<>(columnNames);
this.rows = new ArrayList<>(rows);
}
public void addColumn(String name) {
addColumn(name, columnNames.size() - 1);
}
public void addColumn(String name, int columnIndex) {
columnIndex = Math.max(0, Math.min(columnIndex, columnNames.size()));
int rowCount = getRowCount();
List<Object> rows = new ArrayList<>(rowCount);
for (int row = 0; row < rowCount; row++) {
rows.add(null);
}
addColumn(name, rows, columnIndex);
}
public void addColumn(String name, List<Object> rows) {
addColumn(name, rows, columnNames.size());
}
public void addColumn(String name, List<Object> newRows, int columnIndex) {
columnIndex = Math.max(0, Math.min(columnIndex, columnNames.size()));
columnNames.add(columnIndex, name);
int rowCount = getRowCount();
for (int row = 0; row < rowCount; row++) {
List<Object> rowData = rows.get(row);
Object value = null;
if (row < newRows.size()) {
value = newRows.get(row);
}
rowData.add(columnIndex, value);
}
fireTableStructureChanged();
}
public void removeColumn(int columnIndex) {
if (columnIndex < 0 || columnIndex >= columnNames.size()) {
return;
}
int rowCount = getRowCount();
for (int row = 0; row < rowCount; row++) {
List<Object> rowData = rows.get(row);
rowData.remove(columnIndex);
}
columnNames.remove(columnIndex);
fireTableStructureChanged();
}
#Override
public int getRowCount() {
return rows.size();
}
#Override
public int getColumnCount() {
return columnNames.size();
}
#Override
public String getColumnName(int column) {
if (column >= columnNames.size()) {
return super.getColumnName(column);
}
return columnNames.get(column);
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
return rows.get(rowIndex).get(columnIndex);
}
}
}
Thanks to camickr for knocking my head back in place, I really just had to set the model to CustomTableModel so I could cast it back using getModel() as well. It now works using the answer in here. If you're using NetBeans, be sure to edit the autogenerated code yourself and change...
contentTable.setModel(new TableModel(
new Object [][] {
},
new String [] {
}
));
to
contentTable.setModel(new CustomTableModel(
new Object [][] {
},
new String [] {
}
));
I have a problem in my code that when using cell edit not allowed then the column size does not work properly
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import java.awt.Dimension;
import java.util.ArrayList;
import javax.swing.table.DefaultTableModel;
import javax.swing.ListSelectionModel;
public class cTable extends JPanel {
private final int keyIndex;
private final int keyIncrement;
private ArrayList<String> tHeaderTitle;
private ArrayList<Integer> tHeaderWidth;
DefaultTableModel dataModel = new DefaultTableModel() {
#Override
public boolean isCellEditable(int rowIndex, int mColIndex) {
return false;
}
};
JTable table = new JTable(dataModel);
public cTable(ArrayList<String> THeaderTitle, ArrayList< Integer> THeaderWidth, int KeyIndex, int KeyIncrement) {
if (THeaderTitle.isEmpty()) {
tHeaderTitle.add("Title1");
} else {
tHeaderTitle = new ArrayList<>(THeaderTitle);
}
if (THeaderWidth.isEmpty()) {
tHeaderWidth.add(30);
} else {
tHeaderWidth = new ArrayList<>(THeaderWidth);
}
keyIndex = KeyIndex;
keyIncrement = KeyIncrement;
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.setAutoscrolls(true);
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setAutoscrolls(true);
for (int i = 0; i < tHeaderTitle.size(); i++) {
dataModel.addColumn(tHeaderTitle.get(i));
table.getColumnModel().getColumn(i).setPreferredWidth(tHeaderWidth.get(i));
}
table.setPreferredScrollableViewportSize(new Dimension(TotalWidth(tHeaderWidth) + 110, 100));
table.getTableHeader().setResizingAllowed(false);
table.getTableHeader().setReorderingAllowed(false);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setRowHeight(25);
add(scrollPane);
}
public void addColumn(String cName, int cWidth) {
dataModel.addColumn(cName);
table.getColumnModel().getColumn(dataModel.getColumnCount() - 1).setPreferredWidth(cWidth);
table.setPreferredScrollableViewportSize(new Dimension(TotalWidth(tHeaderWidth) + cWidth, 150));
tHeaderWidth.add(cWidth);
}
public void addRow(String[] values) {
boolean exists = false;
if (dataModel.getRowCount() == 0) {
dataModel.addRow(values);
} else {
for (int i = 0; i < dataModel.getRowCount(); i++) {
if (dataModel.getValueAt(i, keyIndex) == values[keyIndex]) {
dataModel.setValueAt(Integer.valueOf(String.valueOf(dataModel.getValueAt(i, keyIncrement))) + 1, i, keyIncrement);
exists = true;
}
}
if (!exists) {
dataModel.addRow(values);
}
}
}
private int TotalWidth(ArrayList<Integer> wl) {
int sum = 0;
for (Integer wl1 : wl) {
sum += wl1;
}
return sum;
}
}
and in my main frame class mainClass I used the cTable component to create my customized table but the column size does not appear to be right , actually it does not work and the cells should be editable
import javax.swing.JPanel;
........
public class mainClass {
public static void main(String args[]) {
......
// initialize frame settings to add a cTable component
......
ArrayList<Integer> TheaderWidth = new ArrayList<>();
ArrayList<String> TheaderTitle = new ArrayList<>();
cTable InvTable;
TheaderTitle.add("id");
TheaderTitle.add("Qty");
TheaderTitle.add("Description");
TheaderTitle.add("Notes");
TheaderWidth.add(30);
TheaderWidth.add(50);
TheaderWidth.add(200);
TheaderWidth.add(100);
InvTable = new cTable(TheaderTitle, TheaderWidth, 1, 2);
InvTable.setBounds(10, 10, 600, 300);
panel1.add(InvTable);
InvTable.setVisible(true);
this.pack();
}
}
I don't know how to go about i have this frame i wish to populate a JTable and add a checkbox.
public static void update_table() {
try {
String sql="SELECT * FROM equipments";
PreparedStatement update = con.prepareStatement(sql);
ResultSet result = update.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(result));
table.setVisible(true);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I assume you mean to want to add an additional column not found in the database containing a check box so you can select rows?
If so then you can use a wrapper TableModel.
Here is an example that might help:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
public class CheckBoxWrapperTableModel extends AbstractTableModel
{
private ArrayList<Boolean> checkBoxes = new ArrayList<>();
private DefaultTableModel model;
private String columnName;
public CheckBoxWrapperTableModel(DefaultTableModel model, String columnName)
{
this.model = model;
this.columnName = columnName;
for (int i = 0; i < model.getRowCount(); i++)
checkBoxes.add( Boolean.FALSE );
}
#Override
public String getColumnName(int column)
{
return (column > 0) ? model.getColumnName(column - 1) : columnName;
}
#Override
public int getRowCount()
{
return model.getRowCount();
}
#Override
public int getColumnCount()
{
return model.getColumnCount() + 1;
}
#Override
public Object getValueAt(int row, int column)
{
if (column > 0)
return model.getValueAt(row, column - 1);
else
{
Object value = checkBoxes.get(row);
return (value == null) ? Boolean.FALSE : value;
}
}
#Override
public boolean isCellEditable(int row, int column)
{
if (column > 0)
return model.isCellEditable(row, column - 1);
else
return true;
}
#Override
public void setValueAt(Object value, int row, int column)
{
if (column > 0)
model.setValueAt(value, row, column - 1);
else
{
checkBoxes.set(row, (Boolean)value);
}
fireTableCellUpdated(row, column);
}
#Override
public Class getColumnClass(int column)
{
return (column > 0) ? model.getColumnClass(column - 1) : Boolean.class;
}
public void removeRow(int row)
{
checkBoxes.remove(row);
fireTableRowsDeleted(row, row);
model.removeRow(row);
}
private static void createAndShowGUI()
{
// Create the table with check marks in the first column
DefaultTableModel model = new DefaultTableModel(5, 1);
for (int i = 0; i < model.getRowCount(); i++)
{
model.setValueAt("" + i, i, 0);
}
CheckBoxWrapperTableModel wrapperModel = new CheckBoxWrapperTableModel(model, "Select");
JTable table = new JTable(wrapperModel);
// Add button to delete selected rows
JButton button = new JButton( "Delete Selected Rows" );
button.addActionListener( new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
for (int i = table.getRowCount() - 1; i >= 0; i--)
{
Boolean selected = (Boolean)table.getValueAt(i, 0);
System.out.println(selected + " : " + i);
if (selected)
{
wrapperModel.removeRow(i);
}
}
}
});
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( new JScrollPane( table ) );
frame.add( button, BorderLayout.PAGE_END );
frame.pack();
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater( () -> createAndShowGUI() );
/*
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
*/
}
}
If the model works then you would us the model with code like:
//table.setModel(DbUtils.resultSetToTableModel(result));
TableModel utilsModel = DbUtils.resultSetToTableModel(result);
TableModel wrapperModel = new CheckBoxWrapperTableModel(utilsModel, "Select");
table.setModel( wrapperModel );
I have been thinking a lot to solve this mistake. But unfortunately I came to final cnclusion that I need help of professionals.
Please, copy,paste this code to see issue:
public class DateFormatDemo extends JFrame
{
private JTable dataSearchResultTable;
public DateFormatDemo()
{
JButton updateTable = new JButton("Update table");
updateTable.setMaximumSize(updateTable.getPreferredSize());
updateTable.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
updateMyTableModel();
}
});
JPanel panel = new JPanel(new GridLayout(2, 1, 5, 10));
panel.setPreferredSize(new Dimension(500, 300));
panel.add(new JScrollPane(initDataSearchResultTable()));
panel.add(updateTable);
super.getContentPane().add(panel);
super.pack();
super.setDefaultCloseOperation(EXIT_ON_CLOSE);
super.setVisible(true);
}
private JTable initDataSearchResultTable()
{
dataSearchResultTable = new JTable();
// dataSearchResultTable.setAutoCreateColumnsFromModel(false);
dataSearchResultTable.setSelectionBackground(new Color(0xaaaaff));
dataSearchResultTable.setFillsViewportHeight(true);
dataSearchResultTable.setRowSelectionAllowed(true);
dataSearchResultTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
dataSearchResultTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
return dataSearchResultTable;
}
void updateMyTableModel()
{
TableModel tableModel = dataSearchResultTable.getModel();
TableColumnModel columnModel = dataSearchResultTable.getColumnModel();
if (tableModel instanceof MyTableModel) {
((MyTableModel) tableModel).updateModel();
this.initColumnWidths(tableModel, columnModel);
} else {
tableModel = new MyTableModel();
dataSearchResultTable.setModel(tableModel);
this.makeColumnsNotResizable(columnModel);
this.initColumnWidths(tableModel, columnModel);
}
}
private void makeColumnsNotResizable(TableColumnModel columnModel)
{
for (int i = 0; i < columnModel.getColumnCount(); i++) {
if (i == 0 || i == 1) {
columnModel.getColumn(i).setResizable(false);
}
}
}
private void initColumnWidths(TableModel tableModel, TableColumnModel columnModel)
{
TableColumn column = null;
Component comp = null;
int cellWidth = 0;
int headerWidth = 0;
TableCellRenderer headerRenderer = dataSearchResultTable.getTableHeader().getDefaultRenderer();
for (int i = 0; i < columnModel.getColumnCount(); i++) {
column = columnModel.getColumn(i);
comp = headerRenderer.getTableCellRendererComponent(null, column.getHeaderValue(), false, false, -1, 0);
headerWidth = comp.getPreferredSize().width;
Class<?> columnClass = tableModel.getColumnClass(i);
for (int j = 0; j < tableModel.getRowCount(); j++) {
comp = dataSearchResultTable.getDefaultRenderer(columnClass).getTableCellRendererComponent(
dataSearchResultTable, tableModel.getValueAt(j, i), false, false, j, i);
int width = comp.getPreferredSize().width;
// we cache width of first row. And compare widths of next
// rows with width of first.
// If some row has greater width it becomes width of whole
// row(unless header has greater width)
if (cellWidth < width || j == 0) {
cellWidth = width;
}
}
System.out
.println("columnClass=" + columnClass + ",headerWidth=" + headerWidth + ",cellWidth=" + cellWidth);
if (headerWidth > cellWidth) {
TableCellRenderer centeredRenderer = dataSearchResultTable.getDefaultRenderer(columnClass);
if (centeredRenderer instanceof DefaultTableCellRenderer) {
((DefaultTableCellRenderer) centeredRenderer).setHorizontalAlignment(SwingConstants.CENTER);
column.setCellRenderer(centeredRenderer);
column.setPreferredWidth(headerWidth);
}
} else {
column.setPreferredWidth(cellWidth + 5);
}
}
}
class MyTableModel extends AbstractTableModel
{
private String[] columnNames = { "First Name", "Last Name", "Timestamp", "Number", "Vegetarian" };
private Object[][] data = new Object[5][];
void updateModel()
{
data = new Object[][] {
{ "Vova", "KipokKipokKipokKipok", "2013-04-12 11:20:41", new Integer(5), new Boolean(true) },
{ "Olia", "Duo", "2010-01-11 11:11:41", new Integer(3), new Boolean(false) },
{ "Oksana", "Stack", "2012-04-12 11:20:41", new Integer(2), new Boolean(false) },
{ "Petro", "White", "2010-04-12 11:20:21", new Integer(20), new Boolean(true) },
{ "Ivan", "Brown", "2011-04-11 11:20:41", new Integer(10), new Boolean(true) } };
fireTableDataChanged();
}
public int getColumnCount()
{
return columnNames.length;
}
public int getRowCount()
{
return data.length;
}
public String getColumnName(int col)
{
return columnNames[col];
}
public Object getValueAt(int row, int col)
{
if (data.length > 0 && data[0] != null) {
return data[row][col];
}
return null;
}
/*
* JTable uses this method to determine the default renderer/ editor for
* each cell. If we didn't implement this method, then the last column
* would contain text ("true"/"false"), rather than a check box.
*/
public Class getColumnClass(int c)
{
Object valueAt = getValueAt(0, c);
return valueAt == null ? Object.class : valueAt.getClass();
}
/*
* Don't need to implement this method unless your table's editable.
*/
public boolean isCellEditable(int row, int col)
{
// Note that the data/cell address is constant,
// no matter where the cell appears onscreen.
if (col < 2) {
return false;
} else {
return true;
}
}
/*
* Don't need to implement this method unless your table's data can
* change.
*/
public void setValueAt(Object value, int row, int col)
{
if (data.length > 0 && data[0] != null) {
data[row][col] = value;
fireTableCellUpdated(row, col);
}
}
}
public static void main(String[] args) throws ParseException
{
new DateFormatDemo();
}
}
Now please click twice on that big button called 'Update Table'. As you see column that should display checkbox as it holds boolean values do not do that but instead displays String true or false.
This code emulates my real workflow.
So, how to update tablemodel to have boolean columns with checkbozes.
Thanks!
take this as simple start point
import java.awt.*;
import java.util.Random;
import java.util.Vector;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellRenderer;
public class Forum implements ListSelectionListener {
private JFrame frame = new JFrame("Frame");
private JPanel fatherCenter = new JPanel();
private JScrollPane tableScroll = new JScrollPane();
private MyTableModel tableModel;
private JTable dialogTable;
private ListSelectionModel lsDialog;
private Color clr;
private Color clr1;
private void addData() {
Runnable doRun1 = new Runnable() {
#Override
public void run() {
tableModel.resetTable();
Vector<String> tbl = new Vector<String>();
Vector<Object> tbl1 = new Vector<Object>();
Random rnd = new Random();
tbl.add("Integer");
tbl.add("Double");
tbl.add("Boolean");
tbl.add("Boolean");
tbl.add("String");
tableModel.setColumnNames(tbl);
for (int row = 0; row < 30; row++) {
tbl1 = null;
tbl1 = new Vector<Object>();
tbl1.addElement(row + 1);
tbl1.addElement(rnd.nextInt(25) + 3.14);
tbl1.addElement((row % 3 == 0) ? false : true);
tbl1.addElement((row % 5 == 0) ? false : true);
if (row % 7 == 0) {
tbl1.add(("Canc"));
} else if (row % 6 == 0) {
tbl1.add(("Del"));
} else {
tbl1.add(("New"));
}
tableModel.addRow(tbl1);
}
addTableListener();
}
};
SwingUtilities.invokeLater(doRun1);
}
private void addTableListener() {
tableModel.addTableModelListener(new TableModelListener() {
#Override
public void tableChanged(TableModelEvent tme) {
if (tme.getType() == TableModelEvent.UPDATE) {
System.out.println("");
System.out.println("Cell " + tme.getFirstRow() + ", "
+ tme.getColumn() + " changed. The new value: "
+ tableModel.getValueAt(tme.getFirstRow(),
tme.getColumn()));
}
}
});
}
#Override
public void valueChanged(ListSelectionEvent le) {
int row = dialogTable.getSelectedRow();
int col = dialogTable.getSelectedColumn();
String str = "Selected Row(s): ";
int[] rows = dialogTable.getSelectedRows();
for (int i = 0; i < rows.length; i++) {
str += rows[i] + " ";
}
str += "Selected Column(s): ";
int[] cols = dialogTable.getSelectedColumns();
for (int i = 0; i < cols.length; i++) {
str += cols[i] + " ";
}
str += "Selected Cell: " + dialogTable.getSelectedRow() + ", " + dialogTable.getSelectedColumn();
System.out.println(str);
Object value = dialogTable.getValueAt(row, col);
System.out.println(String.valueOf(value));
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
Forum osFrame = new Forum();
}
});
}
public Forum() {
tableModel = new MyTableModel();
dialogTable = new JTable(tableModel) {
private static final long serialVersionUID = 1L;
#Override
public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
Component comp = super.prepareRenderer(renderer, row, column);
JComponent jc = (JComponent) comp;//for Custom JComponent
if (!isRowSelected(row)) {
int modelRow = convertRowIndexToModel(row);
boolean type = (Boolean) getModel().getValueAt(modelRow, 2);
boolean type1 = (Boolean) getModel().getValueAt(modelRow, 3);
comp.setForeground(Color.black);
if ((type) && (!type1)) {
comp.setBackground(clr1);
} else if ((!type) && (type1)) {
comp.setBackground(Color.orange);
} else if ((!type) || (!type1)) {
comp.setBackground(Color.red);
} else {
comp.setBackground(row % 2 == 0 ? getBackground() : getBackground().darker());
}
dialogTable.convertRowIndexToView(0);
} else {
comp.setForeground(Color.blue);
}
if (!isCellEditable(row, column)) {
comp.setForeground(Color.red);
comp.setBackground(Color.magenta);
}
return comp;
}
};
tableScroll = new JScrollPane(dialogTable, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
tableScroll.setBorder(null);
dialogTable.getTableHeader().setReorderingAllowed(false);
dialogTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
lsDialog = dialogTable.getSelectionModel();
dialogTable.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
dialogTable.setRowHeight(20);
dialogTable.setRowMargin(2);
dialogTable.setPreferredScrollableViewportSize(dialogTable.getPreferredSize());
ListSelectionModel rowSelMod = dialogTable.getSelectionModel();
//ListSelectionModel colSelMod = dialogTable.getColumnModel().getSelectionModel();
rowSelMod.addListSelectionListener(this);
//colSelMod.addListSelectionListener(this);
fatherCenter = new JPanel();
fatherCenter.setLayout(new BorderLayout(10, 10));
fatherCenter.add(tableScroll, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout(10, 10));
frame.add(fatherCenter);
frame.setPreferredSize(new Dimension(400, 660));
frame.pack();
frame.setLocation(150, 150);
frame.setVisible(true);
addData();
}
private class MyTableModel extends AbstractTableModel {
private static final long serialVersionUID = 1L;
private Vector<Vector<Object>> _data;
private Vector<String> _colNames;
private boolean[] _columnsVisible = {true, true, true, true, true};
public MyTableModel() {
_colNames = new Vector<String>();
_data = new Vector<Vector<Object>>();
}
public MyTableModel(Vector<String> colnames) {
_colNames = colnames;
_data = new Vector<Vector<Object>>();
}
public void resetTable() {
_colNames.removeAllElements();
_data.removeAllElements();
}
public void setColumnNames(Vector<String> colNames) {
_colNames = colNames;
fireTableStructureChanged();
}
public void addRow(Vector<Object> data) {
_data.add(data);
fireTableRowsInserted(_data.size() - 1, _data.size() - 1);
}
public void removeRowAt(int row) {
_data.removeElementAt(row);
fireTableRowsDeleted(row - 1, _data.size() - 1);
}
#Override
public int getColumnCount() {
return _colNames.size();
}
#Override
public Class<?> getColumnClass(int colNum) {
switch (colNum) {
case 0:
return Integer.class;
case 1:
return Double.class;
case 2:
return Boolean.class;
case 3:
return Boolean.class;
default:
return String.class;
}
}
#Override
public boolean isCellEditable(int row, int colNum) {
switch (colNum) {
case 2:
return false;
default:
return true;
}
}
#Override
public String getColumnName(int colNum) {
return _colNames.get(colNum);
}
#Override
public int getRowCount() {
return _data.size();
}
#Override
public Object getValueAt(int row, int col) {
Vector<Object> value = _data.get(row);
return value.get(col);
}
#Override
public void setValueAt(Object newVal, int row, int col) {
Vector<Object> aRow = _data.elementAt(row);
aRow.remove(col);
aRow.insertElementAt(newVal, col);
fireTableCellUpdated(row, col);
}
public void setColumnVisible(int index, boolean visible) {
_columnsVisible[index] = visible;
fireTableStructureChanged();
}
}
}
Your problem in getColumnClass method as you see you also return Object because of that you also get String columns.
You can determine that method in next way:
#Override
public Class<?> getColumnClass(int arg0) {
return longValues[arg0].getClass();
}
Or return Classes for your columns in another way. But you must to determine this Classes while cunstruct your model.
I have created my JTable like this:
String[] columns = {"Country", "Continent", "Latitude", "Longitude"};
String[][] data = {{"A","B","C","D"}};
table = new JTable(data,columns);
JScrollPane spTable = new JScrollPane(table);
panel2.add(spTable);
Now I want to change the look of the table in such a way that rows will be exchanged with columns, meaning that the table will have 4 rows and 1 column. Could not find such function between member methods, is it possible? Thanks.
To do that, I would consider a custom TableModel which can handle a "toggled" state.
From your example, the result may be surprizing but this code shows you the general idea and allows you to swap rows and columns with a button.
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.AbstractTableModel;
public class TestTable {
private static class TogglingTableModel extends AbstractTableModel {
private boolean toggled = false;
private final Object[][] data;
private final Object[] columnNames;
public TogglingTableModel(Object[][] data, Object[] columnNames) {
this.columnNames = columnNames;
this.data = data;
normalizeData();
}
private void normalizeData() {
for (int i = 0; i < data.length; i++) {
Object[] o = data[i];
if (o.length < columnNames.length) {
data[i] = Arrays.copyOf(o, columnNames.length);
}
}
}
#Override
public String getColumnName(int column) {
if (toggled) {
Object valueAt;
if (column == 0) {
valueAt = columnNames[0];
} else {
valueAt = data[column - 1][0];
}
return valueAt != null ? valueAt.toString() : null;
} else {
Object object = columnNames[column];
return object != null ? object.toString() : null;
}
}
#Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return true;
}
#Override
public int getColumnCount() {
if (toggled) {
return data.length + 1;
} else {
return columnNames.length;
}
}
#Override
public int getRowCount() {
if (toggled) {
return columnNames.length - 1;
} else {
return data.length;
}
}
#Override
public Object getValueAt(int row, int column) {
if (toggled) {
if (column == 0) {
return columnNames[row + 1];
} else {
return data[column - 1][row + 1];
}
} else {
return data[row][column];
}
}
#Override
public void setValueAt(Object aValue, int row, int column) {
if (toggled) {
if (column == 0) {
columnNames[row + 1] = aValue;
} else {
data[column - 1][row + 1] = aValue;
}
} else {
data[row][column] = aValue;
}
}
public boolean isToggled() {
return toggled;
}
public void toggle() {
toggled = !toggled;
fireTableStructureChanged();
}
}
private TogglingTableModel tableModel;
public TestTable() {
JFrame frame = new JFrame(TestTable.class.getSimpleName());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
String[] columns = { "Country", "Continent", "Latitude", "Longitude" };
String[][] data = { { "A" }, { "B" }, { "C" }, { "D" }, { "E" } };
tableModel = new TogglingTableModel(data, columns);
JTable table = new JTable(tableModel);
JPanel buttonPanel = new JPanel();
JButton togglingButton = new JButton("Toggle table");
togglingButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
tableModel.toggle();
}
});
buttonPanel.add(togglingButton);
frame.add(new JScrollPane(table));
frame.add(buttonPanel, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
TestTable fs = new TestTable();
}
});
}
}