I'm trying to set a RowSorter on my Jtable, I used the method setAutoCreateRowSorter(Boolean b) to sort the rows
table.setAutoCreateRowSorter(true);
But when I make the table as rawSorted, I get a strange error!
The conflict is visible when I want to delete a line, I used fireTableRowsDeleted().
int raw = table.getSelectedRow(); // the index of raw that i want to delete it
System.out.println(raw);
model.delte_raw(raw); // model is my table model
public void delte_raw(int raw)
{
if (!ls.isEmpty()) {
this.fireTableRowsDeleted(raw+1, raw);
ls.remove(raw);
}
I want to show you what result return the code as above in 2 cases:
Case 1:
When I make my table as not rawsorted:
table.setAutoCreateRowSorter(false);
when I delete a line, it all works successfully.
Case 2:
When I make my table as rawsorted:
table.setAutoCreateRowSorter(true);
when I delete a line, I get the error as below:
Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Invalid range
at javax.swing.DefaultRowSorter.checkAgainstModel(DefaultRowSorter.java:921)
at javax.swing.DefaultRowSorter.rowsDeleted(DefaultRowSorter.java:878)
at javax.swing.JTable.notifySorter(JTable.java:4277)
at javax.swing.JTable.sortedTableChanged(JTable.java:4121)
at javax.swing.JTable.tableChanged(JTable.java:4398)
at javax.swing.table.AbstractTableModel.fireTableChanged(AbstractTableModel.java:296)
at javax.swing.table.AbstractTableModel.fireTableRowsDeleted(AbstractTableModel.java:261)
I think that the error is in my defaultRowSorter, so I defined my specific cellRenderer as below:
// final TableCellRenderer r = table.getTableHeader().getDefaultRenderer();
//TableCellRenderer wrapper = new TableCellRenderer() {
// private Icon ascendingIcon = new ImageIcon("images/e.png");
// private Icon descendingIcon = new ImageIcon("images/e.png");
//
// #Override
// public Component getTableCellRendererComponent(JTable table,
// Object value, boolean isSelected, boolean hasFocus,
// int row, int column)
// {
// Component comp = r.getTableCellRendererComponent(table, value, isSelected,
// hasFocus, row, column);
// if (comp instanceof JLabel) {
// JLabel label = (JLabel) comp;
// label.setIcon(getSortIcon(table, column));
// }
// return comp;
// }
//
// /**
// * Implements the logic to choose the appropriate icon.
// */
// private Icon getSortIcon(JTable table, int column) {
// SortOrder sortOrder = getColumnSortOrder(table, column);
// if (SortOrder.UNSORTED == sortOrder) {
// return null;
// }
// return SortOrder.ASCENDING == sortOrder ? ascendingIcon : descendingIcon;
// }
//
// private SortOrder getColumnSortOrder(JTable table, int column) {
// if (table == null || table.getRowSorter() == null) {
// return SortOrder.UNSORTED;
// }
// List<? extends RowSorter.SortKey> keys = table.getRowSorter().getSortKeys();
// if (keys.size() > 0) {
// RowSorter.SortKey key = keys.get(0);
// if (key.getColumn() == table.convertColumnIndexToModel(column)) {
// return key.getSortOrder();
// }
// }
// return SortOrder.UNSORTED;
// }
//
//};
//table.getTableHeader().setDefaultRenderer(wrapper);
But again, the same error!
Why do I get this error? I googled it a lot, but either I used the wrong keywords or there are no simple solutions on the internet.
In your table model:
public void delte_raw(int raw) {
if (!ls.isEmpty()) {
this.fireTableRowsDeleted(raw+1, raw); // why raw+1 ???
ls.remove(raw);
}
}
As your table model extends from AbstractTableModel and looking at fireTableRowsDeleted(int firstRow, int lastRow) javadoc:
Notifies all listeners that rows in the range [firstRow, lastRow],
inclusive, have been deleted.
So it should be:
public void delte_raw(int raw) {
if (!ls.isEmpty()) {
ls.remove(raw); // remove the row index from the List and then fire the event
fireTableRowsDeleted(raw, raw);
}
}
Knowing the exception source: looking at DefaultRowSorter.checkAgainstModel(int firstRow, int endRow) implementation:
private void checkAgainstModel(int firstRow, int endRow) {
if (firstRow > endRow || firstRow < 0 || endRow < 0 ||
firstRow > modelRowCount) {
throw new IndexOutOfBoundsException("Invalid range");
}
}
As you can see, calling this method with [raw+1,raw] range causes an IndexOutOfBoundsException.
Edit
As #mKorbel masterfully points out, I've totally overlooked this:
int raw = table.getSelectedRow(); // this is the index in the view
model.delte_raw(raw); // convert raw in the right model index is needed
You need to convert raw in the right model index. Otherwise it can cause side effects since in a sorted table is most likely the selected index in the view be different than its related model's index:
int raw = table.getSelectedRow(); // this is the index in the view
model.delte_raw(table.convertRowIndexToModel(raw)); // perfect
See JTable.convertRowIndexToModel(int viewRowIndex)
Related
I have a JTable which I create dynamically from List<String> objects. I do this probably completely wrong but it works. The only thing I can't get to work is adding Images to some of the cells.
All it does is, it adds the ImageIcon Object name as String to the cells. See my code below.
private static Image doneImage = getIconImage("doneImage");
private static Image notDoneImage = getIconImage("notDoneImage");
private DefaultTableModel model = new DefaultTableModel(){
#Override
public Class<?> getColumnClass(int column){
if ((column & 1) != 0 ){
return ImageIcon.class;
}else{
return String.class;
}
}
};
initTables();
JTable table = new JTable();
table.setModel(model);
private void initTables(){
model.addRow(new Object[]{});
int rowsToAdd = 0;
int rowCount = 0;
int columnId = 0;
for(HouseObject aHouse : houses){
for(RoomObject aRoom : aHouse.getRooms()){
model.addColumn(null);
model.addColumn(aRoom.getId());
model.setValueAt(aRoom.getId(), 0, columnId);
if (rowCount < aRoom.getEvents().size()){
rowsToAdd = aRoom.getEvents().size() - model.getRowCount();
for(int i = 0; i <= rowsToAdd; i++){
model.addRow(new Object[]{});
}
rowCount = model.getRowCount();
}
for(int i = 0; i < aRoom.getEvents().size(); i++){
model.setValueAt(aRoom.getEvents().get(i).getId(), i+1, columnId);
for(String houseDone : housesDone){
if(aRoom.getEvents().get(i).getId().contains(houseDone)){
model.setValueAt(doneImage , i+1, columnId+1); // this does not work
}else{
model.setValueAt(notDoneImage, i+1, columnId+1);
}
}
}
columnId = columnId+2;
}
}
}
You need to install renderer for your table
Here is the renderer:
public class IconTableCellRenderer extends DefaultTableCellRenderer {
#Override
protected void setValue(Object value) {
if (value instanceof Icon) {
setText(null);
setIcon((Icon) value);
} else {
super.setValue(value);
}
}
}
And so you must install it:
JTable table = new JTable();
table.setModel(model);
table.setDefaultRenderer(ImageIcon.class, new IconTableCellRenderer());
I have a JTable which I create dynamically from List objects.
Well you can't just add Strings to the table since then image will need to be added as an ImageIcon. So you would need a List so you can add String and Icon values.
Then you need to override the getColumnClass(...) method of your TableModel to return Icon.class for the column that contains the Icon. The table will then use the appropriate renderer for the Icon.
See: How to set icon in a column of JTable? for a working example.
I recently learned that I can create a custom DefaultTableCellRenderer class for a JTable.
However, my code only colors the entire row but not the specific columns / cells I want to color based on a condition.
How can I specify the row and column in the DefaultTableCellRenderer class I created?
So here are the classes I created.
public class Schedule extends JPanel(){
public Schedule(){
schedulesJtbl.setDefaultRenderer(Object.class, new ScheduleTableCellRenderer());
int startTime = 1230, endTime = 1330;
int jtStartTime = scheduleJtbl.getValueAt(0,1);
int jtEndTime = scheduleJtbl.getValueAt(0,2);
int conflictCheck = 0;
// duplicate startTime and endTime
if((startTime == jtStartTime) && (endTime == jtEndTime)){
conflictCheck++
ScheduleTableCellRenderer.setConflict(conflictCheck);
}
//duplicate startTime
else if(startTime == jtStartTime){
conflictCheck++
ScheduleTableCellRenderer.setConflict(conflictCheck);
}
}
and here's the ScheduleTableCellRenderer
public class ScheduleTableCellRenderer extends DefaultTableCellRenderer {
static int conflict = 0;
#Override
public Component getTableCellRendererComponent(
JTable table, Object value,
boolean isSelected, boolean hasFocus,
int row, int col) {
Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
if (conflict > 0) {
c.setBackground(Color.RED);
} else if (conflict == 0) {
c.setBackground(Color.GREEN);
}
return c;
}
public static void setConflict(int aConflict) {
conflict = aConflict;
}
}
If it's only startTime(as second condition on if) that duplicated, how can I color only column 2 but not the entire row just like what is happening right now on my JTable.
I hope you can help me.
Thank you.
schedulesJtbl.setDefaultRenderer(Object.class, new ScheduleTableCellRenderer());
That sets the default renderer for all Objects in any row/column.
To set the renderer for a specific column you do:
table.getColumnModel().getColumn(???).setCellRenderer( ... );
You also need to reset the default background:
if (conflict > 0) {
c.setBackground(Color.RED);
} else if (conflict == 0) {
c.setBackground(Color.GREEN);
} else {
c.setBackgrund( table.getBackground() );
}
Is it possible to fill JTable in such a way that each cell contains a String consisted of two lines?
String cellText = "Line 1 \n Line 2";
In my JTable I see cellText displayed as a single line.
You'll want to use a custom JTextArea renderer.
http://www.coderanch.com/t/340609/GUI/java/JTable-Custom-Cell-Renderer-JTextArea
This is one I've used over the years:
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.util.*;
public class TextAreaRenderer extends JTextArea implements TableCellRenderer {
private final DefaultTableCellRenderer adaptee = new DefaultTableCellRenderer();
/** map from table to map of rows to map of column heights */
private final Map cellSizes = new HashMap();
public TextAreaRenderer() {
setLineWrap(true);
setWrapStyleWord(true);
}
public Component getTableCellRendererComponent(
JTable table, Object obj, boolean isSelected,
boolean hasFocus, int row, int column) {
// set the colours, etc. using the standard for that platform
adaptee.getTableCellRendererComponent(table, obj,
isSelected, hasFocus, row, column);
setForeground(adaptee.getForeground());
setBackground(adaptee.getBackground());
setBorder(adaptee.getBorder());
setFont(adaptee.getFont());
setText(adaptee.getText());
// This line was very important to get it working with JDK1.4
TableColumnModel columnModel = table.getColumnModel();
setSize(columnModel.getColumn(column).getWidth(), 100000);
int height_wanted = (int) getPreferredSize().getHeight();
addSize(table, row, column, height_wanted);
height_wanted = findTotalMaximumRowSize(table, row);
if (height_wanted != table.getRowHeight(row)) {
table.setRowHeight(row, height_wanted);
}
return this;
}
#SuppressWarnings("unchecked")
private void addSize(JTable table, int row, int column, int height) {
Map rows = (Map) cellSizes.get(table);
if (rows == null) {
cellSizes.put(table, rows = new HashMap());
}
Map rowheights = (Map) rows.get(new Integer(row));
if (rowheights == null) {
rows.put(new Integer(row), rowheights = new HashMap());
}
rowheights.put(new Integer(column), new Integer(height));
}
/**
* Look through all columns and get the renderer. If it is
* also a TextAreaRenderer, we look at the maximum height in
* its hash table for this row.
*/
private int findTotalMaximumRowSize(JTable table, int row) {
int maximum_height = 0;
Enumeration columns = table.getColumnModel().getColumns();
while (columns.hasMoreElements()) {
TableColumn tc = (TableColumn) columns.nextElement();
TableCellRenderer cellRenderer = tc.getCellRenderer();
if (cellRenderer instanceof TextAreaRenderer) {
TextAreaRenderer tar = (TextAreaRenderer) cellRenderer;
maximum_height = Math.max(maximum_height,
tar.findMaximumRowSize(table, row));
}
}
return maximum_height;
}
private int findMaximumRowSize(JTable table, int row) {
Map rows = (Map) cellSizes.get(table);
if (rows == null) {
return 0;
}
Map rowheights = (Map) rows.get(new Integer(row));
if (rowheights == null) {
return 0;
}
int maximum_height = 0;
for (Iterator it = rowheights.entrySet().iterator();
it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
int cellHeight = ((Integer) entry.getValue()).intValue();
maximum_height = Math.max(maximum_height, cellHeight);
}
return maximum_height;
}
}
which you would call with something like this:
table.getColumn("Column").setCellRenderer(new TextAreaRenderer());
JTable Cell data follows html syntax and rules. So you can use <br> to put line separator. hope this helps.
For example i have a JComboBox with values :
{"weapon","armor","weapon"}
If currently selected index is 0 (weapon) and I select index 2 (weapon), it does not trigger an ItemStateChanged in my ItemListener. Although if currently selected index is 0 and I select index 1, it triggers an ItemStateChanged.
Here is my code as of now:
class CBListener implements ItemListener{
#Override
public void itemStateChanged(ItemEvent e){
JComboBox temp = (JComboBox) e.getSource();
int wordIndex = temp.getSelectedIndex(); // index of selected string in the list
int row = sTable.getSelectedRow(); // row of the cell
int col = sTable.getSelectedColumn(); // column of the cell
sTable.setValueAt(listE.get(row)[wordIndex], row, 0);
//System.out.println(listE.get(row)[wordIndex]);
sTable.setValueAt(listI.get(row)[wordIndex], row, 1);
sTable.setValueAt(listD.get(row)[wordIndex], row, 3);
}
}
How can I modify my code so that I can get an index similar to index 2 in my example?
I would still recommend some differentiation between the two items, but if you really want them to be the same, I think you'll have to create an object that has a toString value of "weapon", but for which an equals returns false. Something like:
public BuyableItem( String description, int index ) {
:
:
}
public String toString() {
return this.description;
}
public boolean equals( BuyableItem item ) {
boolean retVal = this.description.equals( item.description );
if( retVal ) {
retVal = this.index == item.index;
}
return retVal;
}
Then your JComboBox values could be
{ new BuyableItem( "weapon", 0 ), new BuyableItem( "armor", 1 ), new BuyableItem( "weapon", 2 ) };
All - I'm trying to set a specific cell's background color after it is clicked AND a successful operation has occurred. I cant seem to do it. Here is the code:
JTable table = new JTable(new DefaultTableModel());
String [] colNames = {"col1", "col2", "ClickMe"};
for (String name : colNames)
table.addColumn(name);
.... some code .....
String [] someArray = {"t", "t2", "t3"};
....
for (int i=0; i<someArray.length;i++) {
Object [] row = new Object[3];
row[0] = "bla";
row[1] = "bla";
row[2] = "Update";
((DefaultTableModel)table.getModel()).addRow(row);
((DefaultTableCellRenderer)gameTable.getCellRenderer(i, 2)).setBackground(Color.LIGHT_GRAY);
((DefaultTableCellRenderer)gameTable.getCellRenderer(i, 2)).setHorizontalAlignment(JLabel.CENTER);
}
table.addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent e) {
int row = gameTable.rowAtPoint(e.getPoint());
int col = gameTable.columnAtPoint(e.getPoint());
if (col == 2) {
Color cellColor = ((DefaultTableCellRenderer)gameTable.getCellRenderer(row,col)).getBackground();
if (cellColor == Color.LIGHT_GREY) {
String val1 = (String)table.getModel().getValueAt(row,1);
String val2 = (String)table.getModel().getValueAt(row,0);
if (doSomething(val1, val2)) { //this returns either true or false, its a Database operations
((DefaultTableCellRenderer)table.getCellRenderer(row, 2)).setBackground(Color.BLUE);
}
}
}
};
Even thought i am specific calling setBackground on a row & column, it makes every cell in every row in column "2" change background color instead of just one specific one.
All the examples with customRenderers seem to just change the color based on when its clicked just change it to something else, i need to do some processing as well.
any thoughts here?
Thanks-
Try this
table.setDefaultRenderer(Object.class, new TableCellRenderer(){
private DefaultTableCellRenderer DEFAULT_RENDERER = new DefaultTableCellRenderer();
private Component comp;
#Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
Component c = DEFAULT_RENDERER.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if(isSelected){
c.setBackground(Color.YELLOW);
}else{
if (row%2 == 0){
if (column==2){
c.setBackground(Color.WHITE);
}
else {
c.setBackground(Color.LIGHT_GRAY);
} } }
return c;
}
});