Input validation using TableCellEditor in jTables - java

I have a JTable with 3 columns. One on the columns must have an integer value and I must validate the input before the cell loses its focus.
I've used cell editor and overrided the stopCellEditing() function. I've wrote the validation in stopCellEditing and it does keep the focus on the cell but but my problem is this:
the column cannot accept more than one value (if I move to editing another cell the content disappears!!)
I cannot hit enter if I'm editing one of the cells in this column!
this is my editor class:
public class MyEditor extends DefaultCellEditor implements TableCellEditor {
public MyEditor() {
super(new JTextField());
}
#Override
public boolean stopCellEditing() {
Object obj = delegate.getCellEditorValue();
if (obj is not an integer) {
return false;
}
return true;
}
and this is how I'm using in in my Frame:
studentsTable.getColumnModel().getColumn(2).setCellEditor(new
MyEditor());
Plz help me :)

One on the columns must have an integer value
No need to write a custom editor for this.
All you need to do is override the getColumnClass() method of JTable or your TableModel and the table will use the supplied Integer editor.
Regarding the code you posted:
It won't compile since your if condition is not valid. We want real code so we can spot possible logic errors. The code should also be posted in the form of an SSCCE.
There is no need to reference the delegate variable. Just invoke the getCellEditor() method directly.
Don't know if it makes a difference bu when I override stopCellEditing(), instead of returning true I use:
return super.stopCellEditing();

Related

Java JTable enabled but not editable with a TableCellRenderer and a defaultTableModel

I'm using TableCellRenderer to render a button in a cell for a JTable created with Matisse in netbeans.
My problem is ... When a double click on the button, I can reach the text field behind. So I want to set the textfield not editable.
For now, my setEnabled are on true: table_watchlistMain.setEnabled(true); I need that because I want to user to be eable to select a row ...
I'm using a DefaultTableModel... do I need to make my own model?
I'm just searching a solution to put the jtable enabled, but not editable. this is possible??
The DefaultTableModel.isCellEditable() method always returns true:
Returns true regardless of parameter values.
So, yes, you should create your own model, for example:
public class MyTableModel extends DefaultTableModel
{
#Override
public boolean isCellEditable(int row, int column)
{
return false;
}
}

JFace - How can I make only one column editable in TreeViewer based on checkbox value from another column in the same row?

I have a TreeViewer which has two columns: ProximityClustersColumn: which has names as String, selectionColumn: which has checkbox as shown in the figure
TreeViewer
I have two questions:
On clicking the selection column's checkbox, the corresponding name of ProximityClustersColumn should become editable.
For eg: When I click on the checkbox corresponding to "Studium organisieren-Formelles", the cell "Studium organisieren-Formelles" should become editable.
Also, as seen in the figure, a check must be made such that only one value in the group, whose checkbox is checked becomes editable.
In other words, for each group, only one category name can be checked and that corresponding name should be editable.
For eg:
If you look at the second group, there are two proximity Cluster names, i.e "Infos für Studis" and "Finanzielles im Studium", along with their respective checkboxes. Now, I can choose one among the two names, by selecting the corresponding checkbox. Suppose, I click on the checkbox corresponding to "Infos für Studis", only that cell should become editable.
The main idea is that : I should be able to select only one name from each group and edit it.
I have tried EditingSupport as suggested by #keyur, but the "canEdit" method is not called at all.
My LabelProvider extends ColumnLabelProvider and implements ITableLabelProvider. My ContentProvider implements ITreeContentProvider.
Is there any reason why EditingSupport will fail?
public class ProximityClustersEditingSupport extends EditingSupport{
private TreeViewer viewer;
private CellEditor editor;
public ProximityClustersEditingSupport(ColumnViewer columnViewer, TreeViewer treeViewer) {
super(columnViewer);
this.viewer = treeViewer;
this.editor = new TextCellEditor(treeViewer.getTree());
}
#Override
protected CellEditor getCellEditor(Object element) {
return new TextCellEditor();
}
#Override
protected boolean canEdit(Object element) {
return true;
}
#Override
protected Object getValue(Object element) {
if(element instanceof ProbeSort)
return ((ProximityClusters)element).proximityClusterNames;
return element;
}
#Override
protected void setValue(Object element, Object value) {
if (element instanceof ProbeSort)
{
((ProximityClusters)element).setProximityClusterNames(String.valueOf(value));
}
viewer.update(element, null);
}
}
I think I need more information to answer it completely. First of all is that Treeviewer or Tableviewer. To me it looks like TableViewer.
What is the expected behavior of the cell when you mean editable. Those cells which are not editable should have disable type foreground colored text and the one which is editable can have normal foreground color say black. Only when user changes to focus (if tab is supported) or by clicking on the cell it is better to show the editable text where user can select the text and change/edit it. And pressing Enter key or Tab Key program can accept the change. Is that what you are looking for?
I guess I didnt get the question. Can you give example from the above figure. Like what is group?
I think EditingSupport will be useful for you.
You can create your concrete EditingSupport class and assign it to your column. It has method "canEdit" through which you can control the editing dynamically.
So what you have to do is to store the boolean flag in the model from checkbox status or read the check box status directly and return false/true value , which will enable/disable editing.
The program in the link shows all possible Tree viewer related implementations. Copy paste the program into a new java class and run as java application. This one example solved all tree related issues i had in my implementation.

GWT Custom Cell in CellList - render() not being called

I'm having trouble figuring out why my render method isn't being called. Here is my custom cell that extends AbstractCell, broken down to its simplest form.
public class FormHistoryCell<T> extends AbstractCell<T> {
#Override
public void render(com.google.gwt.cell.client.Cell.Context context, T value, SafeHtmlBuilder sb) {
System.out.println("Rendering customer cell...");
if (value == null) {
return;
}
}
}
Here is the snipet in my code which creates an instance of "FormHistoryCell" and attempts to add it to a CellList.
#UiFactory
CellList<FormHistoryCell> initList() {
FormHistoryCell formHistoryCell = new FormHistoryCell();
CellList historyList = new CellList<FormHistoryCell>(formHistoryCell);
return historyList;
}
I have tried different things like adding a constructor that takes a String argument, etc. The constructor is called, but the render method is not. Looking at that Abstract class it extends, it seems the render method is called within the "setValue" method, but didn't see where that is called in other custom cell extensions whose render methods seem to be getting called just fine. I'm sure I'm missing something obvious here but can't figure out what. Please help.
Based on the code you provided, there is no reason for a browser to call the render method of your cell. You simply passed a reference to an object FormHistoryCell to your CellList. The render method is only needed when a browser has to display a cell and its content. This happens when you add data to your CellList, as #outellou suggested.

Remove HTML from JTable CellEditor

I have a JTable and some editable cells which are dynamically formatted with very specific HTML based on some business rules.
However, when you edit these cells all the HTML is in the CellEditor. I just want the plain text in the CellEditor.
I am trying to do this to the entire table. Here is the code I used. I threw together an extended DefaultCellEditor but its still showing the HTML. I don't even see the debugger entering the getCellEditorValue() method. What do I do?
public class MyTable extends JTable
{
public MyTable()
{
MyTable.setCellEditor(new DefaultCellEditor(new JTextField())
{
#Override
public Object getCellEditorValue() {
// get content of textField
String str = (String) super.getCellEditorValue();
if (str == null) {
return null;
}
if (str.length() == 0) {
return null;
}
//remove HTML and return plain text
return Jsoup.parse(str).text();
}
});
}
}
I'm not sure where things are going awry; a complete example may shed some light. The normal editing sequence is outlined here, suggesting that you should probably create your own renderer and editor:
class MyRenderer extends DefaultTableCellRenderer {…}
class MyEditor extends DefaultCellEditor {…}
and apply them as follows:
table.setDefaultRenderer(String.class, new MyRenderer());
table.setDefaultEditor(String.class, new MyEditor());
Be certain that your TableModel returns the correct type token from getColumnClass().

How to add a function in jTable that sorts the column?

I know that by using JTable the column is sorted when we click on the column heading, but what I want is that, when I right-click on the column name a function name 'sort' should be displayed. Any suggestion in doing it?
Start by adding a MouseListener to the table. See How to write mouse listeners
You will need to translate the click point to a column, see JTable#columnAtPoint.
You will then need to update the SortKey for the table. Check out Sorting and Filtering for an example
If I understand you correctly, you want to sort by some explicit action (triggered f.i. in a popup) instead of by the normal left-click.
If so, the tricky part is to force the ui-delegate to do nothing. There are two options:
hook into the default mouse listener installed by the ui delegate, as described in a recent QA
let the ui do its stuff, but fool it by a sorter implementation that doesn't follow the rules (beware: that's as dirty as the first approach!)
The mis-behaving sorter:
public class MyTableRowSorter extends TableRowSorter {
public MyTableRowSorter(TableModel model) {
super(model);
}
/**
* Implemented to do nothing to fool tableHeader internals.
*/
#Override
public void toggleSortOrder(int column) {
}
/**
* The method that really toggles, called from custom code.
*
* #param column
*/
public void realToggleSortOrder(int column) {
super.toggleSortOrder(column);
}
}
// usage
final JTable table = new JXTable(new AncientSwingTeam());
table.setRowSorter(new MyTableRowSorter(table.getModel()));
Action toggle = new AbstractAction("toggleSort") {
#Override
public void actionPerformed(ActionEvent e) {
JXTableHeader header = SwingXUtilities.getAncestor(
JXTableHeader.class, (Component) e.getSource());
Point trigger = header.getPopupTriggerLocation();
int column = trigger != null ? header.columnAtPoint(trigger) : -1;
if (column < 0) return;
int modelColumn = header.getTable().convertColumnIndexToModel(column);
((MyTableRowSorter) header.getTable().getRowSorter())
.realToggleSortOrder(modelColumn);
}
};
JPopupMenu menu = new JPopupMenu();
menu.add(toggle);
table.getTableHeader().setComponentPopupMenu(menu);
Yeah, couldn't resist throwing in some SwingX api, lazy me :-) With plain Swing, you'll have to write some lines more but the basics are the same: install the tricksy sorter and use its custom toggle sort to really sort whereever needed, f.i. in a mouseListener.

Categories