JTable prevent all sorting - java

Is it possible to prevent sorting all together on the JTable? Basically I don't want anything to happen when the user clicks the table header, and for the content to be in a static order.

See the Javadoc:
public void setRowSorter(RowSorter sorter)
Parameters: sorter - the RowSorter; null turns sorting off

Basically I don't want anything to happen when the user clicks the table header, and for the content to be in a static order.
basically JTable haven't any Sorter, you have to remove codelines
- JTable#setAutoCreateRowSorter(true);
- table.setRowSorter(sorter);
- custom Comparator added as MouseEvent to the JTableHeader
have look at and read JTable tutorial about Sorting and Filtering

The best and simple way to disable sorting when user clicks on any table header columns:
first you need to create a mouse click listener on the table header
inside of it make only mouse click left avaible (with SwingUtilities)
insert this line of code
yourTableVariable.setRowSorter(null);
Practical example:
yourTableVariable.getTableHeader().addMouseListener(new MouseAdapter() //here you make the click avaible ONLY on Table Header
{
#Override
public void mouseClicked(MouseEvent arg0)
{
if (SwingUtilities.isLeftMouseButton(arg0)) //here you select the mouse left click action
{
yourTableVariable.setRowSorter(null); //here is disableing the sorting
}
}
});

Related

JTable if any row is selected

I am trying to figure out how to add logic to a JTable via an "if" statement that checks to see if ANY row is selected. I know how to check if a specific row is selected but I can't seem to figure out how to check all rows.
if(tbl.isRowSelected(0)){
Obviously that is checking for a specific row.
I've also tried something like
if(tbl.isRowSelected(0-2000)){
This did not work nor did I expect it to work.
The reason for this is that I'm setting up the table so that when the user clicks a row and then hits an "edit" button a second table will appear with more data related to the row they selected. (Gets complicated here with 2D arrays inside of a hash map but I first need to get by this simple problem).
Thanks for the help in advance!
This should be possible with a ListSelectionModel, which can be retrieved using JTable::getSelectionModel()
So you can call table.getSelectionModel().isSelectionEmpty() to find out if any row is selected.
Use :
table.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
public void valueChanged(ListSelectionEvent event) {
// do some actions here, for example
// print first column value from selected row
System.out.println(table.getValueAt(table.getSelectedRow(), 0).toString());
}
});
use table.getSelectedRow() it returns the index of the selected row
and getSelectedColumn() return the selected columns
and there is getSelectedRows() it return index arrays of selected rows
int[] indexs=table_name.getSelectedRows();
//all the selected row are here no need to go throw
//all your rows to see if they are selected or not
for(int index_row:rows){
//you code here
}

Transfer Focus at first Row of jTable in Swing

I want to pass the focus to 1st row of JTable. I can't use editCellAt(row,column) method because I don't want to allow user to change content of table. changeSelection(row,column,false, false) method also does not work properly.
Please suggest me some way to transfer focus to first row.
I have textfield and table. Initially my control is at textfield. If I press ENTER,control should go at first row of table. I have provided the code below. Please help me out.
private void txtRawMaterial(java.awt.event.KeyEvent evt) //txtRawMaterial is textfield
{
if (evt.getKeyCode()==KeyEvent.VK_ENTER)
{
if(table.getRowCount()>0) //table is jTable
{
table.requestFocus();
}
}
}
The two concepts of focus (of the JTable in its role as component) and selection (of rows/columns) are not necessarily related, if you want both you'll have to invoke separate methods to reach both:
table.requestFocus();
table.changeSelection(0, 0, false, false);
Also note that the focused cell is not a focusOwner in the usual sense. Instead, it is the lead of both column- and rowSelection models that typically has a visual clue like a thicker/different border than the others.

create link in table cell and open float popup by click from it

I have a CellTable and need a column with hyper links and onclick handlers inside cells.
1st question, what am doing wrong if I have:
Column<MyObject, Anchor> linkColumn = new Column<MyObject, Anchor>(
new AnchorCell()) {
#Override
public Anchor getValue(final obj) {
Anchor link = new Anchor("link");
link.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
Window.alert("clicked ");
}
});
return link;
}
};
cellTable.addColumn(linkColumn, "link column");
...
public class AnchorCell extends AbstractCell<Anchor> {
#Override
public void render(Context context, Anchor h, SafeHtmlBuilder sb) {
sb.append(SafeHtmlUtils.fromTrustedString(h.toString()));
}
}
-but clicking to link - happens nothing
and 2nd question: what's better way to open float (based on div or so, not separated browser window) pupup with text contents from that ClickHandler?
In a CellTable, you aren't adding the Anchor widget to the table. You're just adding some HTML. None of the widget's functions will work as they normally would, because the widget is not actually in the table.
You can override onBrowserEvent to get events like clicking on the cells. These events still happen because they are native to the browser and don't need the widget framework to propagate. I think this is the best way to achieve the effect you want.
I have a similar setup as you. A CellTable (now a DataGrid) with hyperlinks in it, but I want to popup an editor widget when the user clicks in the cell but not on the link-y bit. If he clicks on the link, I want the normal HTML behaviour.
Create your column using the ClickableTextCell class. What's stored in the cell? A string ID into my database of user records, which includes the name and email of the user. When I create the column, I override the render method so that the information is rendered as a email link:
Column<RowType, ColumnType> emailColumn = new Column<RowType, ColumnType>(new ClickableTextCell()){
#Override
public void render(Context context, T object, SafeHtmlBuilder sb) {
/* Code that pulls the value in this column at this row, uses
* it to look up the name and the email, then does sb.appendX
* to build up the "<a href='emaillink'>name</a>" SafeHtml
* construction.
*/
}
};
Actually, I have a subclass of Column, but you get the idea.
Voila, an active HTML link on your page, but a clickable text cell underneath. I found this a lot easier than dealing with browser events.
I use the same structure for many of my cells. ClickableTextCells underneath, and type-specific rendering code to present it to the user in the format expected. In particular, we have a dynamic picklist type of field -- that is, the picklist is not known until the click occurs. The standard selectionCell requires the list of picks to be established once at construction time, which is what got me to this solution. So instead of a standard SelectionCell dropdown, which wouldn't work anyway without some serious work**, I use this technique. When the ClickableTextCell fires, I have set the FieldUpdater to construct a popup with a DataGrid in it, this DataGrid listing the current set of legal values for this selection (as determined by the current state of the database). When the user makes his selection and hits the Save button, the popup closes, the middleware is called to update his choice, the updated row data is returned via that RPC call, the data returned being used to update the internal client-side database, which triggers an update of all the ListDataProviders driving the DataGrids, which automatically updates the main DataGrid (and any other DataGrid potentially visible on the screen).
Actually, my solution has extended the ClickableTextCell into a DoubleClickableTextCell so that you need to double-click to activate the editor. Not required, of course, but it allows for the user to idly click around the grid without popups exploding in front of him.
** Besides the dynamic aspect, this dynamic selections can be very long lists, so a dropdown is a poor choice. Better to present a DataGrid that the user can scroll through, search, filter, and so on.

Adding a row to a jTable on downarrow at bottom

I have a jTable which currently displays and allows editing of a database table, I am now trying to sort adding tuples.
I am trying to get it to automatically add a row on downarrow at the bottom. So if I am at the bottom on the table and click my down arrow a new row will appear below. I just can't figure out how to do it.
Thanks
James
Action handling of JTable happens in javax.swing.plaf.basic.BasicTableUI. In your case, you probably need to register a new action for SCROLL_DOWN_CHANGE_SELECTION. In the action, check whether the current selection == last row of the table.
If that doesn't work, set a breakpoint in javax.swing.plaf.basic.BasicTableUI.Actions.actionPerformed(ActionEvent) to see which action is really executed.
JTable has a default Action for the down arrow key. If you want to change this behaviour then you need to create a custom Action. You can do this easily by using the Wrapping Actions concept to leverage the default code.
You can also look at Table Tabbing for a working example of wrapping an Action. You code for the Action would be much simpler and would be something like:
if (last row is selected)
add a new row to the table
invoke the default down arrow action
You'll need to create a KeyListener and add this to your table:
public void keyReleased(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_DOWN)
// check if selected table row = last row and if so: add new row to table model
}
greetz,
Stijn

Override list selection in Swing

I want to make list selection such that when I first select an item it get selected after that when I select second item then both should get selected that is first selection should remain as it is. I have set list selection mode to multiple selection. But still has to press ctrl key to do the thing. I want to do it without pressing ctrl key.
How to remain list item selected?
Here is the line where I set the selection mode:
list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
Edit:
AS suggested by StanislavL I tried following but it did not worked for me.
DefaultListSelectionModel model = new DefaultListSelectionModel();
model.removeSelectionInterval(0, 2);
user_list.setSelectionModel(model);
It is a real well known convention that multi select requires pressing the Ctrl key. Same with using the Shift key to select a range of values.
Personally I would never spend effort on changing this behaviour, because it would confuse users that are already familiar with other applications.
Try to replace ListSelectionModel in the list. Use
public void setSelectionModel(ListSelectionModel selectionModel)
You can use the DefaultListSelectionModel and override
public void removeSelectionInterval(int index0, int index1)
call super.remove() if the items are already selected.

Categories