Issue when putting a JLabel inside a Swing table - java

I'm trying to put a JLabel inside my Swing JTable but what I get is apparently the name of the object instead:
This is the class I used to load the JLabel into my table:
/**
* Main Class.
*/
public class Test extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private MyTable tableDest;
private MyTable tableSource;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
Test frame = new Test();
frame.setVisible(true);
}
catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
* #throws Exception
*/
public Test() throws Exception {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JSplitPane splitPane = new JSplitPane();
splitPane.setResizeWeight(0.5);
contentPane.add(splitPane, BorderLayout.CENTER);
tableSource = new MyTable(true);
splitPane.setRightComponent(tableSource);
tableDest = new MyTable(false);
splitPane.setLeftComponent(tableDest);
TransferHandler transferHandler = new MyTransferHandler();
tableSource.setDragEnabled(true);
tableSource.setTransferHandler(transferHandler);
tableSource.setDropMode(DropMode.ON);
tableDest.setDragEnabled(true);
tableDest.setTransferHandler(transferHandler);
tableDest.setDropMode(DropMode.ON);
}
}
/**
* Class for The Table
*/
class MyTable extends JTable {
private static final long serialVersionUID = 1L;
public MyTable(boolean withData) throws Exception {
this( new MyTableModel(withData));
}
public MyTable(MyTableModel tableModel) {
super(tableModel);
setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
}
#Override
public MyTableModel getModel() {
return (MyTableModel)super.getModel();
}
}
/**
* Class for The JPanel import into The table
*/
class MyTableModel extends AbstractTableModel {
private static final long serialVersionUID = 1L;
private JLabel[] dataSource = new JLabel[16];
public MyTableModel(boolean fill) {
if(fill) {
for(int i = 0; i < dataSource.length; i++) {
dataSource[i] = new JLabel("<html>Text color: <font color='red'>red</font></html>");
}
}
}
#Override
public int getRowCount() {
return 4;
}
#Override
public int getColumnCount() {
return 4;
}
#Override
public Object getValueAt(int row, int col) {
int index = getIndex(row, col);
return dataSource[index];
}
#Override
public void setValueAt(Object aValue, int row, int col) {
int index = getIndex(row, col);
dataSource[index] = (JLabel)aValue;
}
#Override
public Class<?> getColumnClass(int col) {
return JLabel.class;
}
public void removeAt(int row, int col) {
int index = getIndex(row, col);
dataSource[index] = null;
fireTableCellUpdated(row, col);
}
private int getIndex(int row, int col) {
return row*4 + col;
}
}
/**
* Class for the drag'n drop Stuff
*/
class MyTransferHandler extends TransferHandler {
private static final long serialVersionUID = 1L;
#Override
public int getSourceActions(JComponent comp) {
return MOVE;
}
int selectedRow;
int selectedCol;
#Override
public Transferable createTransferable(JComponent comp) {
System.out.println("createTransferable");
MyTable table = (MyTable)comp;
selectedRow = table.getSelectedRow();
selectedCol = table.getSelectedColumn();
String text = (String) table.getValueAt(selectedRow, selectedCol);
System.out.println("DND init for: " + text);
return new StringSelection(text);
}
#Override
public void exportDone(JComponent comp, Transferable trans, int action) {
System.out.println("exportDone");
if (action == MOVE) {
MyTable table = (MyTable)comp;
table.getModel().removeAt(selectedRow, selectedCol);
}
}
#Override
public boolean canImport(TransferSupport support) {
//System.out.println("canImport");
return support.isDrop();
}
#Override
public boolean importData(TransferSupport support) {
System.out.println("importData");
if(canImport(support)) { //to prevent from paste's
DropLocation dl = support.getDropLocation();
Point dropPoint = dl.getDropPoint();
String data;
try {
data = (String)support.getTransferable().getTransferData(DataFlavor.stringFlavor);
System.out.println("DND received: " + data);
} catch (UnsupportedFlavorException | IOException e) {
return false;
}
MyTable table = (MyTable)support.getComponent();
int row = table.rowAtPoint(dropPoint);
int col = table.columnAtPoint(dropPoint);
MyTableModel model = table.getModel();
Object currentValue = model.getValueAt(row, col);
if(currentValue == null) { //if there's currently no value on that cell
model.setValueAt(data, row, col);
model.fireTableCellUpdated(row, col);
return true;
}
}
return false;
}
}
What am I doing wrong? It's not supposed to display a JPanel instead of this text.

I'm trying to put a JLabel inside my Swing Table but what I get is apparentely the Name of the object instead.
JLabel is the default component for a cell in a JTable. I assume you added a JLabel to the default one, which caused its toString method to be invoked and displayed in the default label.
Here I created a new JTable and put your String in all the cells:
public class Test extends JFrame {
static String data = "<html>Text color: <font color='red'>red</font></html>";
static int size = 4;
public Test() {
JTable table = new JTable(size, size);
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
table.getModel().setValueAt(data, i, j);
}
}
add(table);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
}
public static void main(String[] args) {
new Test();
}
}

Related

How can I Resize a JScrollPane with JTable on it?

I created a JTable with some nice functions. My problem is, that it does not resize when I size the frame where it is on. Can someone help me with my Code so it does resize like it should? I alaready tryed some ideas of posts I found but it did not rly help me. So I have tryed to add the JPanel on another one with some Layout ideas. I have also tryed to use ComponentListeners and setSize on resizeaction.
Code:
public class TableyTable extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
public JTableHeader header;
public JTable table;
public JScrollPane scrollPane;
public JPopupMenu renamePopup;
public JTextField text;
public TableColumn column;
private boolean headerEditable = false;
private boolean tableEditable = false;
public static final Dimension SCREEN_SIZE = Toolkit.getDefaultToolkit().getScreenSize();
public static final int MIN_ROW_HEIGHT = (int)SCREEN_SIZE.getHeight()/36;
public static final int MIN_ROW_WIDTH = (int)SCREEN_SIZE.getWidth()/108;
public TableyTable(int row, int column) {
init(row, column);
}
public void init(int row, int column) {
table = new JTable(row, column) {
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
public boolean isCellEditable(int row, int column) {
if (tableEditable) return true;
return false;
}
};
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.changeSelection(0, 0, false, false);
header = table.getTableHeader();
header.addMouseListener(new MouseAdapter(){
#Override
public void mouseClicked(MouseEvent event) {
if (event.getClickCount() == 2 && headerEditable) {
editColumnAt(event.getPoint());
}
}
});
text = new JTextField();
text.setBorder(null);
text.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (headerEditable) renameColumn();
}
});
table.setRowSelectionAllowed(false);
table.setCellSelectionEnabled(true);
renamePopup = new JPopupMenu();
renamePopup.setBorder(new MatteBorder(0, 1, 1, 1, Color.DARK_GRAY));
renamePopup.add(text);
scrollPane = new JScrollPane( table );
scrollPane.setRowHeaderView(buildRowHeader(table));
table.setRowHeight(MIN_ROW_HEIGHT);
TableColumnModel cm = table.getColumnModel();
for(int i = 0; i < table.getColumnModel().getColumnCount(); i++)
cm.getColumn(i).setWidth(200);
table.setColumnModel(cm);
add(scrollPane);
}
public void setHeaderEditable(boolean b) {
headerEditable = b;
}
public boolean isHeaderEditable() {
return headerEditable;
}
public void setTableEditable(boolean b) {
tableEditable = b;
}
public boolean isTableEditable() {
return tableEditable;
}
private void editColumnAt(Point p) {
int columnIndex = header.columnAtPoint(p);
if (columnIndex != -1) {
column = header.getColumnModel().getColumn(columnIndex);
Rectangle columnRectangle = header.getHeaderRect(columnIndex);
text.setText(column.getHeaderValue().toString());
renamePopup.setPreferredSize(new Dimension(columnRectangle.width, columnRectangle.height - 1));
renamePopup.show(header, columnRectangle.x, 0);
text.requestFocusInWindow();
text.selectAll();
}
}
private void renameColumn() {
column.setHeaderValue(text.getText());
renamePopup.setVisible(false);
header.repaint();
}
private static JList<Object> buildRowHeader(JTable table) {
final Vector<String> headers = new Vector<String>();
for (int i = 0; i < table.getRowCount(); i++) {
String name = "";
if (i < 10) {
name += "0";
}
if (i < 100) {
name += "0";
}
name += i;
headers.add(name);
}
ListModel<Object> lm = new AbstractListModel<Object>() {
/**
*
*/
private static final long serialVersionUID = 1L;
public int getSize() {
return headers.size();
}
public Object getElementAt(int index) {
return headers.get(index);
}
};
final JList<Object> rowHeader = new JList<>(lm);
rowHeader.setOpaque(false);
rowHeader.setFixedCellWidth(TableyTable.MIN_ROW_HEIGHT);
MouseInputAdapter mouseAdapter = new MouseInputAdapter() {
Cursor oldCursor;
Cursor RESIZE_CURSOR = Cursor.getPredefinedCursor(Cursor.S_RESIZE_CURSOR);
int index = -1;
int oldY = -1;
#Override
public void mouseMoved(MouseEvent e) {
super.mouseMoved(e);
int previ = getLocationToIndex(new Point(e.getX(), e.getY() - 3));
int nexti = getLocationToIndex(new Point(e.getX(), e.getY() + 3));
if (previ != -1 && previ != nexti) {
if (!isResizeCursor()) {
oldCursor = rowHeader.getCursor();
rowHeader.setCursor(RESIZE_CURSOR);
index = previ;
}
} else if (isResizeCursor()) {
rowHeader.setCursor(oldCursor);
}
}
private int getLocationToIndex(Point point) {
int i = rowHeader.locationToIndex(point);
if (!rowHeader.getCellBounds(i, i).contains(point)) {
i = -1;
}
return i;
}
#Override
public void mouseReleased(MouseEvent e) {
super.mouseReleased(e);
if (isResizeCursor()) {
rowHeader.setCursor(oldCursor);
index = -1;
oldY = -1;
}
}
#Override
public void mouseDragged(MouseEvent e) {
super.mouseDragged(e);
if (isResizeCursor() && index != -1) {
int y = e.getY();
if (oldY != -1) {
int inc = y - oldY;
int oldRowHeight = table.getRowHeight(index);
int oldNextRowHeight = table.getRowHeight(index+1);
if (oldRowHeight > MIN_ROW_HEIGHT || inc > 0) {
int rowHeight = Math.max(MIN_ROW_HEIGHT, oldRowHeight + inc);
table.setRowHeight(index, rowHeight);
if (rowHeader.getModel().getSize() > index + 1) {
int rowHeight1 = table.getRowHeight(index + 1) - inc;
rowHeight1 = Math.max(MIN_ROW_HEIGHT, rowHeight1);
table.setRowHeight(index + 1, rowHeight1);
}
}
if (table.getRowCount()>index+1)
table.setRowHeight(1+index, oldNextRowHeight);
else System.out.println("HI");
}
oldY = y;
}
}
private boolean isResizeCursor() {
return rowHeader.getCursor() == RESIZE_CURSOR;
}
};
rowHeader.addMouseListener(mouseAdapter);
rowHeader.addMouseMotionListener(mouseAdapter);
rowHeader.addMouseWheelListener(mouseAdapter);
rowHeader.setCellRenderer(new RowHeaderRenderer(table));
rowHeader.setBackground(table.getBackground());
rowHeader.setForeground(table.getForeground());
return rowHeader;
}
static class RowHeaderRenderer extends JLabel implements ListCellRenderer<Object> {
/**
*
*/
private static final long serialVersionUID = 1L;
private JTable table;
RowHeaderRenderer(JTable table) {
this.table = table;
JTableHeader header = this.table.getTableHeader();
setOpaque(true);
setBorder(UIManager.getBorder("TableHeader.cellBorder"));
setHorizontalAlignment(CENTER);
setForeground(header.getForeground());
setBackground(header.getBackground());
setFont(header.getFont());
setDoubleBuffered(true);
}
public Component getListCellRendererComponent(JList<?> list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
setText((value == null) ? "" : value.toString());
setPreferredSize(null);
setPreferredSize(new Dimension((int) getPreferredSize().getWidth(), table.getRowHeight(index)));
list.firePropertyChange("cellRenderer", 0, 1);
return this;
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Tabley");
TableyTable table = new TableyTable(1000, 18278);
table.setHeaderEditable(true);
table.setTableEditable(true);
frame.add(table);
frame.setSize(new Dimension(700, 500));
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
As in the tutorial described, you need to set a LayoutManager and add the JScrollPane accordingly:
setLayout(new BorderLayout());
add(scrollPane,BorderLayout.CENTER);

How to add a table, with one row made of JComboboxes, on top an existing JTable

I am trying to add a one row JTable on top of an existing JTable which is usually created dynamically and which changes its data model quite often.
As you can see the yellow area represents just a row counter and It has been created using this source
The yellow column, therefore has been attached to the main table using the following code:
JTable rowTable = new RowNumberTable(table);
scrollTable.setRowHeaderView(rowTable);
The table columns A, B, C, and so on, if clicked, sort the JTable accordingly and this feature should be maintained (I do not want to put the JCombobox in the table header unless there is a clever way of doing both things).
My aim is to create a JTable with one row (See red row) which has as many columns as the main JTable
EDIT
Here there is the SSCCE
I would like to put JComboBoxes on top of A,B,C,D.....
The class that renders the JComboBoxes is ColumnJComboBoxTable which is called in TableDemo as follow:
//Column JCombobox
JTable columnTable = new ColumnJComboBoxTable(table);
scrollTable.setColumnHeaderView(columnTable);
Right now it is not working as I want (Well, It is not working at all)
Buttons at the top add and remove columns. Therefore if a column is deleted the respective JComboBox must be deleted too.
CODE
TableDemo
package com.table;
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.AbstractAction;
public class TableDemo extends JFrame
{
private static final long serialVersionUID = 1L;
public TableDemo()
{
super("TableDemo");
Object[][] data =
{
{"0","1","2","3","4","5","6","7","8","9","10"},
{"0","1","2","3","4","5","6","7","8","9","10"},
{"0","1","2","3","4","5","6","7","8","9","10"},
{"0","1","2","3","4","5","6","7","8","9","10"},
{"0","1","2","3","4","5","6","7","8","9","10"},
{"0","1","2","3","4","5","6","7","8","9","10"},
{"0","1","2","3","4","5","6","7","8","9","10"},
{"0","1","2","3","4","5","6","7","8","9","10"},
{"0","1","2","3","4","5","6","7","8","9","10"},
{"0","1","2","3","4","5","6","7","8","9","10"},
{"0","1","2","3","4","5","6","7","8","9","10"},
{"0","1","2","3","4","5","6","7","8","9","10"},
{"0","1","2","3","4","5","6","7","8","9","10"},
{"0","1","2","3","4","5","6","7","8","9","10"},
};
String[] columnNames =
{
"A",
"B",
"C",
"D",
"E",
"F",
"G",
"H",
"I",
"J",
"K",
};
final JTable table = new JTable(data, columnNames);
new JPopupMenu();
final JToolBar toolBar = new JToolBar();
final XTableColumnModel columnModel = new XTableColumnModel();
table.setColumnModel(columnModel);
table.createDefaultColumnsFromModel();
toolBar.add(new JButton(new AbstractAction("ALL") {
/**
*
*/
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e) {
columnModel.setAllColumnsVisible();
}
}));
toolBar.add(new JButton(new AbstractAction("Column 0") {
/**
*
*/
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e) {
TableColumn column = columnModel.getColumnByModelIndex(0);
boolean visible = columnModel.isColumnVisible(column);
columnModel.setColumnVisible(column, !visible);
}
}));
toolBar.add(new JButton(new AbstractAction("Column 1") {
/**
*
*/
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e) {
TableColumn column = columnModel.getColumnByModelIndex(1);
boolean visible = columnModel.isColumnVisible(column);
columnModel.setColumnVisible(column, !visible);
}
}));
toolBar.add(new JButton(new AbstractAction("Column 2") {
/**
*
*/
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e) {
TableColumn column = columnModel.getColumnByModelIndex(2);
boolean visible = columnModel.isColumnVisible(column);
columnModel.setColumnVisible(column, !visible);
}
}));
toolBar.add(new JButton(new AbstractAction("Column 3") {
/**
*
*/
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e) {
TableColumn column = columnModel.getColumnByModelIndex(3);
boolean visible = columnModel.isColumnVisible(column);
columnModel.setColumnVisible(column, !visible);
}
}));
toolBar.add(new JButton(new AbstractAction("Column 4") {
/**
*
*/
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e) {
TableColumn column = columnModel.getColumnByModelIndex(4);
boolean visible = columnModel.isColumnVisible(column);
columnModel.setColumnVisible(column, !visible);
}
}));
toolBar.add(new JButton(new AbstractAction("Column 5") {
/**
*
*/
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e) {
TableColumn column = columnModel.getColumnByModelIndex(5);
boolean visible = columnModel.isColumnVisible(column);
columnModel.setColumnVisible(column, !visible);
}
}));
toolBar.add(new JButton(new AbstractAction("Column 6") {
/**
*
*/
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e) {
TableColumn column = columnModel.getColumnByModelIndex(6);
boolean visible = columnModel.isColumnVisible(column);
columnModel.setColumnVisible(column, !visible);
}
}));
toolBar.add(new JButton(new AbstractAction("Column 7") {
/**
*
*/
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e) {
TableColumn column = columnModel.getColumnByModelIndex(7);
boolean visible = columnModel.isColumnVisible(column);
columnModel.setColumnVisible(column, !visible);
}
}));
toolBar.add(new JButton(new AbstractAction("Column 8") {
/**
*
*/
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e) {
TableColumn column = columnModel.getColumnByModelIndex(8);
boolean visible = columnModel.isColumnVisible(column);
columnModel.setColumnVisible(column, !visible);
}
}));
toolBar.add(new JButton(new AbstractAction("Column 9") {
/**
*
*/
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e) {
TableColumn column = columnModel.getColumnByModelIndex(9);
boolean visible = columnModel.isColumnVisible(column);
columnModel.setColumnVisible(column, !visible);
}
}));
toolBar.add(new JButton(new AbstractAction("Column 10") {
/**
*
*/
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e) {
TableColumn column = columnModel.getColumnByModelIndex(10);
boolean visible = columnModel.isColumnVisible(column);
columnModel.setColumnVisible(column, !visible);
}
}));
//Row number
table.setFillsViewportHeight(true);
JScrollPane scrollTable = new JScrollPane(table,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollTable.setViewportView(table);
JTable rowTable = new RowNumberTable(table);
scrollTable.setRowHeaderView(rowTable);
scrollTable.setCorner(JScrollPane.UPPER_LEFT_CORNER, rowTable.getTableHeader());
//Column JCombobox
JTable columnTable = new ColumnJComboBoxTable(table);
scrollTable.setColumnHeaderView(columnTable);
getContentPane().add(toolBar, BorderLayout.NORTH);
getContentPane().add(scrollTable, BorderLayout.CENTER);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
public static void main(String[] args)
{
TableDemo frame = new TableDemo();
frame.pack();
frame.repaint();
frame.setVisible(true);
}
}
XTableColumnModel
The table model has been borrowed here
package com.table;
import javax.swing.table.*;
import java.util.Vector;
import java.util.Enumeration;
public class XTableColumnModel extends DefaultTableColumnModel {
private static final long serialVersionUID = 1L;
protected Vector allTableColumns = new Vector();
XTableColumnModel() {
}
public void setColumnVisible(TableColumn column, boolean visible) {
if(!visible) {
super.removeColumn(column);
}
else
{
int noVisibleColumns = tableColumns.size();
int noInvisibleColumns = allTableColumns.size();
int visibleIndex = 0;
for(int invisibleIndex = 0; invisibleIndex < noInvisibleColumns; ++invisibleIndex) {
TableColumn visibleColumn = (visibleIndex < noVisibleColumns ? (TableColumn)tableColumns.get(visibleIndex) : null);
TableColumn testColumn = (TableColumn)allTableColumns.get(invisibleIndex);
if(testColumn == column) {
if(visibleColumn != column) {
super.addColumn(column);
super.moveColumn(tableColumns.size() - 1, visibleIndex);
}
return;
}
if(testColumn == visibleColumn) {
++visibleIndex;
}
}
}
}
public void setAllColumnsVisible() {
int noColumns = allTableColumns.size();
for(int columnIndex = 0; columnIndex < noColumns; ++columnIndex) {
TableColumn visibleColumn = (columnIndex < tableColumns.size() ? (TableColumn)tableColumns.get(columnIndex) : null);
TableColumn invisibleColumn = (TableColumn)allTableColumns.get(columnIndex);
if(visibleColumn != invisibleColumn) {
super.addColumn(invisibleColumn);
super.moveColumn(tableColumns.size() - 1, columnIndex);
}
}
}
public TableColumn getColumnByModelIndex(int modelColumnIndex) {
for (int columnIndex = 0; columnIndex < allTableColumns.size(); ++columnIndex) {
TableColumn column = (TableColumn)allTableColumns.elementAt(columnIndex);
if(column.getModelIndex() == modelColumnIndex) {
return column;
}
}
return null;
}
public boolean isColumnVisible(TableColumn aColumn) {
return (tableColumns.indexOf(aColumn) >= 0);
}
public void addColumn(TableColumn column) {
allTableColumns.addElement(column);
super.addColumn(column);
}
public void removeColumn(TableColumn column) {
int allColumnsIndex = allTableColumns.indexOf(column);
if(allColumnsIndex != -1) {
allTableColumns.removeElementAt(allColumnsIndex);
}
super.removeColumn(column);
}
public void moveColumn(int oldIndex, int newIndex) {
if ((oldIndex < 0) || (oldIndex >= getColumnCount()) ||
(newIndex < 0) || (newIndex >= getColumnCount()))
throw new IllegalArgumentException("moveColumn() - Index out of range");
TableColumn fromColumn = (TableColumn) tableColumns.get(oldIndex);
TableColumn toColumn = (TableColumn) tableColumns.get(newIndex);
int allColumnsOldIndex = allTableColumns.indexOf(fromColumn);
int allColumnsNewIndex = allTableColumns.indexOf(toColumn);
if(oldIndex != newIndex) {
allTableColumns.removeElementAt(allColumnsOldIndex);
allTableColumns.insertElementAt(fromColumn, allColumnsNewIndex);
}
super.moveColumn(oldIndex, newIndex);
}
public int getColumnCount(boolean onlyVisible) {
Vector columns = (onlyVisible ? tableColumns : allTableColumns);
return columns.size();
}
public Enumeration getColumns(boolean onlyVisible) {
Vector columns = (onlyVisible ? tableColumns : allTableColumns);
return columns.elements();
}
public int getColumnIndex(Object identifier, boolean onlyVisible) {
if (identifier == null) {
throw new IllegalArgumentException("Identifier is null");
}
Vector columns = (onlyVisible ? tableColumns : allTableColumns);
int noColumns = columns.size();
TableColumn column;
for(int columnIndex = 0; columnIndex < noColumns; ++columnIndex) {
column = (TableColumn)columns.get(columnIndex);
if(identifier.equals(column.getIdentifier()))
return columnIndex;
}
throw new IllegalArgumentException("Identifier not found");
}
public TableColumn getColumn(int columnIndex, boolean onlyVisible) {
return (TableColumn)tableColumns.elementAt(columnIndex);
}
}
RowNumberTable
package com.table;
import java.awt.*;
import java.beans.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
public class RowNumberTable extends JTable
implements ChangeListener, PropertyChangeListener, TableModelListener
{
private static final long serialVersionUID = -3837585325898676144L;
private JTable main;
public RowNumberTable(JTable table)
{
main = table;
main.addPropertyChangeListener( this );
main.getModel().addTableModelListener( this );
setFocusable( false );
setAutoCreateColumnsFromModel( false );
setSelectionModel( main.getSelectionModel() );
TableColumn column = new TableColumn();
column.setHeaderValue(" ");
addColumn( column );
column.setCellRenderer(new RowNumberRenderer());
getColumnModel().getColumn(0).setPreferredWidth(50);
setPreferredScrollableViewportSize(getPreferredSize());
}
#Override
public void addNotify()
{
super.addNotify();
Component c = getParent();
// Keep scrolling of the row table in sync with the main table.
if (c instanceof JViewport)
{
JViewport viewport = (JViewport)c;
viewport.addChangeListener( this );
}
}
#Override
public int getRowCount()
{
return main.getRowCount();
}
#Override
public int getRowHeight(int row)
{
int rowHeight = main.getRowHeight(row);
if (rowHeight != super.getRowHeight(row))
{
super.setRowHeight(row, rowHeight);
}
return rowHeight;
}
#Override
public Object getValueAt(int row, int column)
{
return Integer.toString(row + 1);
}
#Override
public boolean isCellEditable(int row, int column)
{
return false;
}
#Override
public void setValueAt(Object value, int row, int column) {}
public void stateChanged(ChangeEvent e)
{
// Keep the scrolling of the row table in sync with main table
JViewport viewport = (JViewport) e.getSource();
JScrollPane scrollPane = (JScrollPane)viewport.getParent();
scrollPane.getVerticalScrollBar().setValue(viewport.getViewPosition().y);
viewport.setBackground(Color.WHITE);
}
public void propertyChange(PropertyChangeEvent e)
{
// Keep the row table in sync with the main table
if ("selectionModel".equals(e.getPropertyName()))
{
setSelectionModel( main.getSelectionModel() );
}
if ("rowHeight".equals(e.getPropertyName()))
{
repaint();
}
if ("model".equals(e.getPropertyName()))
{
main.getModel().addTableModelListener( this );
revalidate();
}
}
#Override
public void tableChanged(TableModelEvent e)
{
revalidate();
}
/*
* Attempt to mimic the table header renderer
*/
private static class RowNumberRenderer extends DefaultTableCellRenderer
{
/**
*
*/
private static final long serialVersionUID = 6579115025835194953L;
public RowNumberRenderer()
{
setHorizontalAlignment(JLabel.CENTER);
}
public Component getTableCellRendererComponent(
JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
if (table != null)
{
JTableHeader header = table.getTableHeader();
if (header != null)
{
setForeground(header.getForeground());
setBackground(header.getBackground());
setFont(header.getFont());
}
}
if (isSelected)
{
setFont( getFont().deriveFont(Font.ITALIC) );
}
setText((value == null) ? "" : value.toString());
//setBorder(UIManager.getBorder("TableHeader.cellBorder"));
return this;
}
}
}
ColumnJComboBoxTable
package com.table;
import java.awt.*;
import java.beans.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
public class ColumnJComboBoxTable extends JTable implements ChangeListener,PropertyChangeListener, TableModelListener
{
private static final long serialVersionUID = -3837585325898676144L;
private JTable main;
public ColumnJComboBoxTable(JTable table)
{
main = table;
main.addPropertyChangeListener( this );
main.getModel().addTableModelListener( this );
setFocusable( false );
setAutoCreateColumnsFromModel( false );
setSelectionModel( main.getSelectionModel() );
for(int i =0; i<main.getModel().getColumnCount();i++)
{
TableColumn column = new TableColumn();
column.setHeaderValue(i);
addColumn( column );
getColumnModel().getColumn(i).setPreferredWidth(50);
column.setCellRenderer(new ColumnJComboBoxRenderer());
column.setHeaderRenderer(new ColumnJComboBoxRenderer());
}
setPreferredScrollableViewportSize(getPreferredSize());
}
#Override
public void addNotify()
{
super.addNotify();
Component c = getParent();
// Keep scrolling of the row table in sync with the main table.
if (c instanceof JViewport)
{
JViewport viewport = (JViewport)c;
viewport.addChangeListener( this );
}
}
#Override
public int getColumnCount()
{
return main.getColumnCount();
}
#Override
public int getRowHeight(int row)
{
int rowHeight = main.getRowHeight(row);
if (rowHeight != super.getRowHeight(row))
{
super.setRowHeight(row, rowHeight);
}
return rowHeight;
}
/*
* No model is being used for this table so just use the row number
* as the value of the cell.
*/
#Override
public Object getValueAt(int row, int column)
{
return Integer.toString(column + 1);
}
/*
* Don't edit data in the main TableModel by mistake
*/
#Override
public boolean isCellEditable(int row, int column)
{
return false;
}
/*
* Do nothing since the table ignores the model
*/
#Override
public void setValueAt(Object value, int row, int column) {}
//
// Implement the ChangeListener
//
public void stateChanged(ChangeEvent e)
{
// Keep the scrolling of the row table in sync with main table
JViewport viewport = (JViewport) e.getSource();
JScrollPane scrollPane = (JScrollPane)viewport.getParent();
scrollPane.getHorizontalScrollBar().setValue(viewport.getViewPosition().x);
}
//
// Implement the PropertyChangeListener
//
public void propertyChange(PropertyChangeEvent e)
{
// Keep the row table in sync with the main table
if ("selectionModel".equals(e.getPropertyName()))
{
setSelectionModel( main.getSelectionModel() );
}
if ("rowHeight".equals(e.getPropertyName()))
{
repaint();
}
if ("model".equals(e.getPropertyName()))
{
main.getModel().addTableModelListener( this );
revalidate();
}
}
//
// Implement the TableModelListener
//
#Override
public void tableChanged(TableModelEvent e)
{
revalidate();
}
/*
* Attempt to mimic the table header renderer
*/
private static class ColumnJComboBoxRenderer extends DefaultTableCellRenderer
{
/**
*
*/
private static final long serialVersionUID = 6579115025835194953L;
public ColumnJComboBoxRenderer()
{
setHorizontalAlignment(JLabel.HORIZONTAL);
}
public Component getTableCellRendererComponent(
JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
if (table != null)
{
JTableHeader header = table.getTableHeader();
if (header != null)
{
setForeground(header.getForeground());
setBackground(header.getBackground());
setFont(header.getFont());
}
}
if (isSelected)
{
setFont( getFont().deriveFont(Font.ITALIC) );
}
setText((value == null) ? "" : value.toString());
return this;
}
}
}
Anyone's help would be highly appreciated
Thanks
Thanks to #mKorbel for the help
Here the code of a solution
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
public class TableFilterRow implements TableColumnModelListener
{
private JTable table;
private JPanel filterRow;
public TableFilterRow(JTable table,JPanel filterRow)
{
this.table = table;
this.filterRow=filterRow;
table.setPreferredScrollableViewportSize(table.getPreferredSize());
table.getColumnModel().addColumnModelListener(this);
table.columnMarginChanged(new ChangeEvent(table.getColumnModel()));
}
#Override
public void columnMarginChanged(ChangeEvent e)
{
TableColumnModel tcm = table.getColumnModel();
int columns = tcm.getColumnCount();
for (int i = 0; i < columns; i++)
{
JComboBox<?> comboBox = (JComboBox<?>) filterRow.getComponent(i);
Dimension d = comboBox.getPreferredSize();
d.width = tcm.getColumn(i).getWidth();
comboBox.setPreferredSize(d);
}
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
filterRow.revalidate();
}
});
}
#Override
public void columnMoved(TableColumnModelEvent e)
{
Component moved = filterRow.getComponent(e.getFromIndex());
filterRow.remove(e.getFromIndex());
filterRow.add(moved, e.getToIndex());
filterRow.validate();
}
#Override
public void columnAdded(TableColumnModelEvent e)
{
}
#Override
public void columnRemoved(TableColumnModelEvent e)
{
}
#Override
public void columnSelectionChanged(ListSelectionEvent e)
{
}
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
JTable table = new JTable(3, 5);
table.setPreferredScrollableViewportSize(table.getPreferredSize());
table.columnMarginChanged(new ChangeEvent(table.getColumnModel()));
ComboFields[] comboFields = ComboFields.values();
JScrollPane scrollPane = new JScrollPane(table);
frame.add(scrollPane, BorderLayout.CENTER);
JPanel filterRow = new JPanel();
filterRow.setLayout(new FlowLayout(FlowLayout.CENTER, 0, 0));
for (int i = 0; i < table.getColumnCount(); i++)
{
filterRow.add(new JComboBox<ComboFields>(comboFields));
}
new TableFilterRow(table, filterRow);
frame.add(filterRow, BorderLayout.NORTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private enum ComboFields{
VALUE_0(0),
VALUE_1(1),
VALUE_2(2),
VALUE_3(3),
VALUE_4(4),
VALUE_5(5);
// Internal state
private int fieldNumber;
private ComboFields(final int fieldNumber)
{
this.setFieldNumber(fieldNumber);
}
#SuppressWarnings("unused")
public int getFieldNumber() {
return fieldNumber;
}
public void setFieldNumber(int fieldNumber)
{
this.fieldNumber = fieldNumber;
}
}
}

Adding multiple JProgressBar to TableColumn of JTable

I have added multiple JProgressBar to TableColumn of JTable.
I am updating all the JProgressBar with data after making certain calculations, but only the last ProgressBar(in this case ProgressBar progressObj4) which is added is getting updated.
How can I update all the ProgressBars?
The basic requirement is that I am displaying the status of file in progress bar while uploading . Currently I am hardcoding 4 progress bars to test if all the progress bars are getting update wrt the status of the file, but I need to create them dynamically. The total no of progress bars wrt the no of files which is getting uploaded. Also, how can I fetch the individual instances of the progress bars & update their status ?
I am attaching the source code of the progressbar getting added to the table column.
//tc = object of TableColumn
progressObj1 = new ProgressBarRenderer("Progress1");
progressObj1.setValue(0);
progressObj1.setStringPainted(true);
progressObj1.setBackground(Color.WHITE);
progressObj1.setBorderPainted(true);
tc.setCellRenderer(progressObj1);
progressObj2 = new ProgressBarRenderer("Progress2");
progressObj2.setValue(0);
progressObj2.setStringPainted(true);
progressObj2.setBackground(Color.WHITE);
progressObj2.setBorderPainted(true);
tc.setCellRenderer(progressObj2);
progressObj3 = new ProgressBarRenderer("Progress3");
progressObj3.setValue(0);
progressObj3.setStringPainted(true);
progressObj3.setBackground(Color.WHITE);
progressObj3.setBorderPainted(true);
tc.setCellRenderer(progressObj3);
progressObj4 = new ProgressBarRenderer("Progress4");
progressObj4.setValue(0);
progressObj4.setStringPainted(true);
progressObj4.setBackground(Color.WHITE);
progressObj4.setBorderPainted(true);
tc.setCellRenderer(progressObj4);
basically there are two ways move with JProgressBar by using SwingWorker and Runnable#Thread, example for SwingWorker
import java.awt.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
public class TableCellProgressBar {
private String[] columnNames = {"String", "ProgressBar"};
private Object[][] data = {{"dummy", 100}};
private DefaultTableModel model = new DefaultTableModel(data, columnNames) {
private static final long serialVersionUID = 1L;
#Override
public Class<?> getColumnClass(int column) {
return getValueAt(0, column).getClass();
}
#Override
public boolean isCellEditable(int row, int col) {
return false;
}
};
private JTable table = new JTable(model);
public JComponent makeUI() {
TableColumn column = table.getColumnModel().getColumn(1);
column.setCellRenderer(new ProgressRenderer());
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
startTask("test");
startTask("error test");
startTask("test");
}
});
JPanel p = new JPanel(new BorderLayout());
p.add(new JScrollPane(table));
return p;
}
//http://java-swing-tips.blogspot.com/2008/03/jprogressbar-in-jtable-cell.html
private void startTask(String str) {
final int key = model.getRowCount();
SwingWorker<Integer, Integer> worker = new SwingWorker<Integer, Integer>() {
private int sleepDummy = new Random().nextInt(100) + 1;
private int lengthOfTask = 120;
#Override
protected Integer doInBackground() {
int current = 0;
while (current < lengthOfTask && !isCancelled()) {
if (!table.isDisplayable()) {
break;
}
if (key == 2 && current > 60) { //Error Test
cancel(true);
publish(-1);
return -1;
}
current++;
try {
Thread.sleep(sleepDummy);
} catch (InterruptedException ie) {
break;
}
publish(100 * current / lengthOfTask);
}
return sleepDummy * lengthOfTask;
}
#Override
protected void process(java.util.List<Integer> c) {
model.setValueAt(c.get(c.size() - 1), key, 1);
}
#Override
protected void done() {
String text;
int i = -1;
if (isCancelled()) {
text = "Cancelled";
} else {
try {
i = get();
text = (i >= 0) ? "Done" : "Disposed";
} catch (Exception ignore) {
ignore.printStackTrace();
text = ignore.getMessage();
}
}
System.out.println(key + ":" + text + "(" + i + "ms)");
}
};
model.addRow(new Object[]{str, 0});
worker.execute();
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new TableCellProgressBar().makeUI());
frame.setSize(320, 240);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class ProgressRenderer extends DefaultTableCellRenderer {
private final JProgressBar b = new JProgressBar(0, 100);
public ProgressRenderer() {
super();
setOpaque(true);
b.setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
}
#Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
Integer i = (Integer) value;
String text = "Completed";
if (i < 0) {
text = "Error";
} else if (i < 100) {
b.setValue(i);
return b;
}
super.getTableCellRendererComponent(table, text, isSelected, hasFocus, row, column);
return this;
}
}
To my knowledge, a renderer applies to all rows in a given column. It seems to me that you would like to apply several renderers to the same column. Furthermore, it also seems that you are attempting to give the cell renderer state.
I believe it will help to make the renderer stateless and have the renderer's method getTableCellRendererComponent() take care of setting the various (JProgressBar) properties based on values from the current row before the renderer paints the cell.
In other words, you should only need to invoke tc.setCellRenderer() once for any given column, and then have your cell renderer to draw the column for any given row (based on, say, the underlying data model for that table).

How to gray-out non-editable cell in jtable?

I want to gray non-editable cell in JTable.
I'm using such TableCellRenderer:
TableColumn column = table.getColumnModel().getColumn(0);
column.setCellRenderer(new GrayableCheckboxCellRenderer());
public class GrayableCheckboxCellRenderer extends JCheckBox implements TableCellRenderer {
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int vRowIndex, int vColIndex) {
boolean editable = isEditable(vRowIndex, vColIndex);
setBackground(editable ? UIManager.getColor("Label.background") : Color.LIGHT_GRAY);
setSelected((Boolean) value);
if (isSelected) {
// TODO: cell (and perhaps other cells) are selected, need to highlight it
}
return this;
}
// perfomance
protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) {}
public void firePropertyChange(String propertyName, boolean oldValue, boolean newValue) {}
public void revalidate() {}
public void validate() {}
}
This works but with one annoying artefact:
Initially "checkbox" is "left-arranged", when I press left mouse button it moves to "center-arranged" and when I release mouse button it moves back to "left-arranged".
How to avoid such annoying artefact and probably there are better simpler solution for my problem?
Return an instance of GrayableCheckboxCellRenderer in a TableCellEditor.
Addendum: Aesthetically, you may want to condition the renderer's and editor's colors based on the defaults provided by the current Look & Feel, for example:
Color hilite = UIManager.getColor("Table.selectionBackground");
simpliest way by using preparedRenderer
import java.awt.*;
import java.util.Random;
import java.util.Vector;
import javax.swing.*;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellRenderer;
public class Forum {
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 void addComponentsToPane(Container pane) {
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);
boolean type2 = (Boolean) getModel().isCellEditable(row, column);
comp.setForeground(Color.black);
if ((type) && (!type1)) {
comp.setBackground(Color.yellow);
} else if ((!type) && (type1)) {
comp.setBackground(Color.orange);
} else if ((!type) || (!type1)) {
comp.setBackground(Color.red);
//} else if ((!type2)) {
//comp.setForeground(Color.red);
//comp.setBackground(Color.magenta);
} else {
comp.setBackground(row % 2 == 0 ? getBackground() : getBackground().darker());
}
dialogTable.convertRowIndexToView(0);
} else {
comp.setForeground(Color.blue);
comp.setBackground(Color.lightGray);
}
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);
fatherCenter = new JPanel();
fatherCenter.setLayout(new BorderLayout(10, 10));
fatherCenter.add(tableScroll, BorderLayout.CENTER);
pane.add(fatherCenter);
}
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("Cell " + tme.getFirstRow() + ", "
+ tme.getColumn() + " changed. The new value: "
+ tableModel.getValueAt(tme.getFirstRow(),
tme.getColumn()));
}
}
});
}
private void createAndShowGUI() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout(10, 10));
addComponentsToPane(frame.getContentPane());
addData();
frame.setLocation(150, 150);
frame.setPreferredSize(new Dimension(400, 646));
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
Forum osFrame = new Forum();
}
public Forum() {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGUI();
}
});
}
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};
myTableModel() {
this.colNames = new Vector<String>();
this.data = new Vector<Vector<Object>>();
}
myTableModel(Vector<String> colnames) {
this.colNames = colnames;
this.data = new Vector<Vector<Object>>();
}
public void resetTable() {
this.colNames.removeAllElements();
this.data.removeAllElements();
}
public void setColumnNames(Vector<String> colNames) {
this.colNames = colNames;
this.fireTableStructureChanged();
}
public void addRow(Vector<Object> data) {
this.data.add(data);
this.fireTableDataChanged();
this.fireTableStructureChanged();
}
public void removeRowAt(int row) {
this.data.removeElementAt(row);
this.fireTableDataChanged();
}
#Override
public int getColumnCount() {
return this.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 this.colNames.get(colNum);
}
#Override
public int getRowCount() {
return this.data.size();
}
#Override
public Object getValueAt(int row, int col) {
Vector<Object> value = this.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) {
this._columnsVisible[index] = visible;
this.fireTableStructureChanged();
}
}
}
Just explicitly setting the alignment in the 'getTableCellRendererComponent()' method solves the problem. Add the below line before returning from the method.
setHorizontalAlignment(SwingConstants.CENTER);

How to auto select the last inserted row in JTable?

Since JTable could be sorted.
How do I set it auto select the last inserted row whenever a row is inserted?
Thanks
your TableModel can retun number of rows, and new/added could be last by using convertRowIndexToView you can get row in TableView, then pass to the changeSelection
public void changeSelection(int rowIndex, int columnIndex, boolean toggle, boolean extend)
EDIT: example (for enjoy harcoded numbersOfRows - 3 instead of correct numbersOfRows - 1):
import java.awt.*;
import java.awt.event.ActionEvent;
import javax.swing.*;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.event.*;
import javax.swing.table.*;
public class TestTableRowTable {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
// UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if (info.getName().equals("Nimbus")) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e1) {
e1.printStackTrace();
}
final JTable table = new JTable(10, 6);
for (int i = 0; i < table.getRowCount(); i++) {
table.setValueAt(i, i, 0);
}
final TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(table.getModel());
table.setRowSorter(sorter);
final AbstractTableModel model = new AbstractTableModel() {
private static final long serialVersionUID = 1L;
#Override
public int getColumnCount() {
return 1;
}
#Override
public Object getValueAt(int row, int column) {
return table.convertRowIndexToModel(row);
}
#Override
public int getRowCount() {
return table.getRowCount();
}
};
JTable headerTable = new JTable(model);
headerTable.setShowGrid(false);
headerTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
headerTable.setPreferredScrollableViewportSize(new Dimension(30, 0));
headerTable.getColumnModel().getColumn(0).setPreferredWidth(30);
headerTable.getColumnModel().getColumn(0).setCellRenderer(new TableCellRenderer() {
#Override
public Component getTableCellRendererComponent(JTable x, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
boolean selected = table.getSelectionModel().isSelectedIndex(row);
Component component = table.getTableHeader().getDefaultRenderer().getTableCellRendererComponent(table, value, false, false, -1, -2);
((JLabel) component).setHorizontalAlignment(JLabel.CENTER);
if (selected) {
component.setFont(component.getFont().deriveFont(Font.BOLD));
} else {
component.setFont(component.getFont().deriveFont(Font.PLAIN));
}
return component;
}
});
table.getRowSorter().addRowSorterListener(
new RowSorterListener() {
#Override
public void sorterChanged(RowSorterEvent e) {
model.fireTableDataChanged();
}
});
table.getSelectionModel().addListSelectionListener(
new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
model.fireTableRowsUpdated(0, model.getRowCount() - 1);
}
});
JScrollPane pane = new JScrollPane(table);
pane.setRowHeaderView(headerTable);
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(pane);
frame.getContentPane().add(new JButton(new AbstractAction("Toggle filter") {
private static final long serialVersionUID = 1L;
private RowFilter<TableModel, Object> filter = new RowFilter<TableModel, Object>() {
#Override
public boolean include(javax.swing.RowFilter.Entry<? extends TableModel, ? extends Object> entry) {
return ((Number) entry.getValue(0)).intValue() % 2 == 0;
//return ((String) entry.getValue(0)).length()>0 ;
//return ((Date) entry.getValue(0)).getTime()< ;
}
};
#Override
public void actionPerformed(ActionEvent e) {
if (sorter.getRowFilter() != null) {
sorter.setRowFilter(null);
TableModel tblModel = table.getModel();
int numbersOfRows = 0;
numbersOfRows = tblModel.getRowCount();
int lastRow = 0;
lastRow = table.convertRowIndexToView(numbersOfRows - 3);
table.changeSelection(lastRow, 0, false, false);
} else {
sorter.setRowFilter(filter);
}
}
}), BorderLayout.PAGE_END);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
private TestTableRowTable() {
}
}
It is hard to answer,because you haven't provided any code, but, if you use some model of JTable you can write some adapter for method insert, I mean for public void insertRow(int row, Vector rowData). Here is present number of row, using this number you can select row. Do you know how to select row ?

Categories