Is there anyway I can highlight a row in JTable? - java

I am currently building a database using JTable and DefaultTableModel. In my program I
have a function which allows users to search the database. I have the search part build but I don't
know how to highlight a row or a cell in the JTable. Can someone please help me?
Thank you

Are you sure you want to highlight as opposed to filter out the extraneous results? If you highlight, you'll have to scroll through the whole list to find all of the matching results, whereas if you filter the display, it's a lot easier to find what you're looking for.
If you go the filtering route I'd look into GlazedLists, a truly great Java library for doing things like dynamic filtering, sorting, etc. of JTables.
If you still want to go the highlighting route, then there's two main ways I see of accomplishing this. The first is to use the ListSelectionModel of the JTable and ensure that all of the matching rows are in the selected set; this will cause them to be visually distinguished with a minimum of coding. On the other hand, as soon as the user drags in the table and selects something else, the visual effect is lost.
The second way to accomplish this would be to use a custom TableCellRenderer that changes how a row is rendered if the row matches your selection criteria. An easy way to do that would be to change the background color.

The Swing tutorial on How to Use Tables has a section on filtering so you can just dislay the data that meet the search criteria. If you want to see all the data, then you just remove the filter.
If you really want to do separate highlighting then I would take a look at the Table Row Rendering approach.

I can tell you how I am doing it.
I implemented my search to work as the search in a document, i.e. finding single result at a time. I am storing the current index of the selected row or starting from the first one if no row was previously selected. Then I have my model implement my interface with functionality to search for next or previous match, example below shows use of find next match method which returns an index of the row in a table where the matching string was found, then I change the selection to it else I clear the selection to let the user know there is no match.
int index = serchableTableModel.findNextMatchIndex(serchedText, currentIndex);
if(index != -1)
table.changeSelection(index, 0, false, false);
else
table.clearSelection();
I hope this sorts your problem.
NOTE: I was not aware of the glazed lists before, they really seem promising. They would have saved me implementing sorting of tables, searching myself.

Related

Auto edit cell in nebula nattable

My nattable is a tree table that has custom root objects. I want to edit a cell in the table. The second column is static. But row index is dynamic. Im not able to get the correct row index for nattable edit after I add an entry into the table. The new row is added based on dialog selection.
Code:
nattableprovider.getSelectionProvider().setSelection(new StructuredSelection(obj));
SelectionLayer selLayer = nattableprovider.getBodyLayer().getSelectionLayer();
PositionCoordinate pos = selLayer.getSelectionAnchor();
nattable.doCommand(newEditCellCommand(nattable, nattable.getConfugRegistry(),nattable.getCellByPosition(2,pos.rowPositon)
First, I don't see a question. You should phrase a question if you expect an answer.
Second, you show some code that probably should trigger a selection and then activate the edit mode, but you do not show the NatTable composition. There is typically a correlation.
Third, not sure if you understand the difference of row index vs. row position. Especially because you retrieve the row position from the SelectionLayer and then want to use it on the NatTable layer. Typically there is a transformation in between, at least if you have a column header. But as you don't give an information on your NatTable composition, hard to tell.
Also if you want to edit something that is not visible, the activation of the edit mode is not possible. But again, hard to say without more details. There could be multiple issues. But I suppose each is somehow related to incorrect position handling.

Tracking data offset of data in a table to retrieve the previous/next subset on table scroll

I am writing a browser based application using GWT and making use of websql (yes, I know it is deprecated). I have created a custom table widget (based on FlexTable) and enabled it to scroll with the help of some CSS trickery. What I am striving to achieve (without much success) is that when the user scrolls to the start/end of the current data in the table, an event is fired and the next subset of X rows is returned from the websql DB and replaces the data currently in the table. In order for this to work, I need to keep track of the data offset in the table widget so that I can pass this to the query and use the limit and offset functions of SQL to return the required data. However, I just cannot seem to get the logic right to implement the data offset tracker within the widget. Another complication is that I need the table to be able to scroll 'into the past' (so to speak), so that it can retrieve data from before the initial start point when the table loads.
I have been at this for a number of days now and just cannot seem to get it right. So I was wondering/hoping that someone might be able to point me in the right direction (PLEASE!).
Thanks in advance
Tim
I am not sure why this is causing a problem.
int page = 0;
// when you hit the bottom
page++;
loadData(page);
// when you hit the top
if (page > 0) {
page--;
loadData(page);
}
Tim I think it is not a good idea controlling the scroll with CSS trickery.
I have done something similar soon and controlling all the logic (pagination, scroll positions,...).
What I suggest to use is a gwt's scrollPanel, a HasData widget (like a cellList) your custom AbstractCell (class which is rendered for each row of your list) and asyncDataProvider ( which gives you the onRangeChange handler for asking to your server when the range data display has changed).
You can force/fire that event when in scrollPanel.addScrollHandler detects you are arriving to the end.
If you want to see all of this in action have a look into (click on source code): http://gwt.googleusercontent.com/samples/Showcase/Showcase.html#!CwCellList
EDIT [according comment below]:
A. If you want to override the data (in the example is X+X+X...) with the new retrieved just maintain always the same range of data displayed [display.setVisibleRange(0, newPageSize);], and start from 0 when you render the new data (on your RangeChange listener).
B. If you need to have control over up and down scrolls instead of taking advantage of the used events internally on the cellList (basically onRangeChange), you can create your custom events and fire them (this option could be easier for your colleagues for understanding everything). And do not worry about controlling up and down scrolls, inside the ShowMorePagerPanel.java you can see a simple example of knowing up and down controls.
Anyway, I did not explain more detailed because I did not see you very convinced to use CellList approach (and I was using my tablet :D ).
If you change your mind, just let me know and I write for you a proper example step by step (this part could be tricky, so if you are lost it is normal ;) ).

how can i programatically select a particular text from JTable when i do search in it?

here are the screenshots of the application
Rows will be displayed in the Table according to the text which is written in the search textfield.
Now i want to mark that particular text as per the shown in the second image with the yellow color
I know how to select a row or a particular cell.
but I don't know how to select a particular text inside the cell of any row in the table.
I am guessing you know how to search in JTable, so I am not pasting code of it here.
You can look over the SwingX library. It has this kind of function as you said predefined it it. You just need to add it to your table. This is where you can find it. Give it a try you will surely like it.
The basic premise would be to use a custom TableCellRenderer that provided the functionality that you require.
The problem is how to implement it.
I would create a TableCellRenderer based on a JTextField, remove it's border and make it transparent. This will allow you to use the text highlighting functionality provided by JTextCompoent to highlight portions of the text, as demonstrated here.
The next problem is then knowing what to highlight. There are a number of possibilities.
You could provide a method in your table model that could return the current text that should be highlighted.
I'd, personally, probably use the JTable#putClientProperty and JTable#getClientProperty methods to seed the search text.
Or, you could actually provide a simple model that directly to the renderer which had a method that returned the current search text. This might actually be more useful as you could link it to field, the method building the filter and the renderers and allow them to simply seed each other

How would I programmatically store and apply a selection in a JTable

I have a program that creates a huge jtable with CellSelection enabled to copy to clipboard. I also have an Action that copies the complete table.
It does so by:
correspondentTable.selectAll();
// then copy
correspondentTable.clearSelection();
It would be very nice if after that the "complex" selection would be restored after this action.
So far I found table.changeselection(row, col, toggle, extend) but I was wondering if there is a "more elegant" way of doing this.
If you are looking for individual cells, you could iterate over the table cells and check them using isCellSelected. Actually, I see no "more elegant" solution than that.
It should be possible to limit the range you need to check:
Use getSelectedRow() to get the minimum index, getSelectedRows() gets you all indices. There are similar functions for columns.
You store these values somewhere and use changeSelection to restore the selection.
Edit: You can get the column model (getColumnModel()) and the selection model (getSelectionModel()), which store the selection value. If you can copy them, you could reapply there values afterwards.

How to indicate that a column in a table is sortable (UI design question)?

In the application that I am working on, there is tabular data (for the record, it is a Java Swing app using JTables). In some cases the data is sortable by clicking on the column headers.
What I want to know is what is a good way to indicate to the user if a given column is sortable or not?
I have come up with the following possibilities.
1) Put an icon in each sortable column indicating it is sortable. I personally do not like this option.
2) Change the mouse cursor into something else when it hovers over the header to indicate it is sortable.
3) Put a note in the tooltip text when hovering over the column saying that it is sortable.
Does anyone have any other suggestions?
Update:
I think a clarification is in order.
My question is not how does one indicate that a given column is currently sorted. That is already implemented via the up/down sort triangle paradigm.
I want to give the user a clue as to which columns can be sorted before they click on the header to sort it.
Update 2:
I think I should explain why I'm not entirely sold on option #1. It seems to me that if one is going to put an icon to indicate which columns are sortable then this will add to visual clutter. In such cases, sometimes the UI changes on "mouse over". Case in point: Windows Vista and 7 allows one to add a filter on a column yet the indicator for this does not appear until you hover over the header with the mouse.
When you're dealing with the UI, you have to put your mind into what the user will expect. I would almost always recommend staying with the paradigms that your users will expect. Therefore I would recommend a version of option 1)
RememberME's post describes how this could work - You can still use arrows in column headers - one option would be to put an arrow icon in the header, but change the state of that icon if it was sorted (e.g. highlight the up or down button if the dataset is currently sorted by this column.)
Edit:
A Windows Explorer example may not be the best example here. My original text quoted below:
In Windows Explorer and almost all
form datagrids there is a small icon,
usually an up or down arrow, that
indicates that a column is sortable.
Experiment with Windows Explorer to
see the way in which this works.
In many apps, triangles indicate sortable so I think that's the best way to convey the information to the user b/c it's a standard they're most likely familiar with.
I think the jquery plugin from DataTables.Net is a good example. You could take a look and see if you like the look/functionality of that and emulate it. Both an up and a down indicate sortable. Just one or the other indicate that it is being sorted. If they column is not sortable, there is no icon at all. Their example also changes the pointer from an arrow to the hand pointer to indicate that you can click on the header.
I think the standard way is essentially option 1: either display the data initially sorted with a little arrow pointing either up or down (ascending/descending), or sort+display the icon as soon as the column header is clicked.
I think having a little arrow or triangle icon below the column heading, which you can click to sort by that column is the best option, as it is easy to see visually and very intuitive to use.
Little triangular up/down sort icons are pretty much standard for sortable table views in desktop applications and web pages. You may not like them, but your users are probably used to them (even if they don't realize it).
You should of course change the mouse cursor over clickable elements.
You should always do 2 for anything clickable.
Number 1 is not bad, typically a triangle pointing up or down depending on the sort order.
To indicate clickability, you could also use blue, underlined text on sortable columns and plain dark gray text on nonsortables -- the http link appearance is a well-known device to virtually all users, but it would not convey sortability, per se. Rather, a user might expect clicking that to take them to some other screen or list, as a hyperlink typically does.
I may be a little dense, but what kinds of columns are not sortable?
Pretty much anything can be sorted; even if there is no strict "greater than" relationship, at least there will be an "equals", and then sorting simply means "bring equal things together".
Strings? Try alphabetical ordering. Images? Sort by percentage of red, green, blue (or if you want to get fancy, compare color histograms). Locations? Use distance to Rome or any other arbitrary location.
Sorting on some columns may be much more useful than sorting on others; but I have a hard time finding a column type were it is important to avoid sorting from taking place.

Categories

Resources