Dynamic styles for GWT cellTable cells - css

I'm having an issue using GWT. I'm building the columns of a cellTable and I want the style of a cell to depends of the value of that cell:
Column<MyProxy, MyProxy> editButtonColumn = new Column<MyProxy, MyProxy>(new ActionCell<MyProxy>("", new ActionCell.Delegate<MyProxy>() {
#Override
public void execute(MyProxy record) {
if (object.isEditable()) {
doSomething(record);
}
}
})) {
#Override
public MyProxy getValue(MyProxy object) {
if (object.isEditable()) {
this.setCellStyleNames("editButtonCell");
}
return object;
}
};
I've checked in debug mode the style "editButtonCell" is applied correctly. But in the HTML generated, the style is missing everytime for the FIRST ROW... It looks like a GWT bug, but maybe you folks have a better explanation.

I haven't checked but most probably the opening of the cell has already been generated by the time getValue is called, so setCellStyleNames will only apply to the remaining cells in the column.
The right way to do it is to override getCellStyleNames of the column to return the CSS class name or not depending on the cell value.
BTW, you can then extend IdentityColumn as the getValue then becomes trivial.

Related

Disable Conditional Formatting for specific column

Starting from WinForms Data Grid v14.2 by enabling the GridOptionsMenu.ShowConditionalFormattingItem property, the Conditional Formatting feature becomes available.
By doing a right click on any column header, the Conditional Formatting menu item is showed up, allowing end-users to apply conditional formatting to grid columns.
My question is that is it possible to disable the feature for a specific column? I'm thinking of having the menu item grayed out, or simply not having it (by hiding it somehow) in the list of items.
I'm aware of the fact that the cells of a specific column can be formatted by the conditional formattings put on other columns by applying the formatting to the entire row. But, my goal is only to make sure the user can not access the functionality for a specific column.
You can remove the corresponding menu-item using the GridView.PopupMenuShowing event:
using System.Windows.Forms;
using DevExpress.XtraGrid.Localization;
using DevExpress.XtraGrid.Menu;
using DevExpress.XtraGrid.Views.Grid;
namespace WindowsFormsApplication2 {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
gridView1.PopupMenuShowing += gridView1_PopupMenuShowing;
}
void gridView1_PopupMenuShowing(object sender, PopupMenuShowingEventArgs e) {
var columnMenu = e.Menu as GridViewColumnMenu;
if(columnMenu != null && columnMenu.Column == this.gridColumn1) {
var conditionalFormattingItem = e.Menu.Items.FirstOrDefault(x => object.Equals(x.Tag, GridStringId.MenuColumnConditionalFormatting));
if(conditionalFormattingItem != null)
conditionalFormattingItem.Visible = false;
}
}
}
}

How to use the Vaadin Testbench with Rich Text Area?

I am using Vaadin Testbench (4.1.0-alpha) for designing some integration test for my application (designed in Vaadin 7.6.1).
In a window, I use a rich test area. The idea is to design a test where the value of this rich text element is changed simulating some user behaviour. But now I realize I cannot find any method for change the value of this element, neither get the current value of the element.
I have tested some methods.getHTML() gets the HTML for the component, no the HTML of the designer. getText() gets the list of elements (font colour, background and other options of the element, but not the content).
Then I expect to have specific class methods for retrieving the value. If I explore the class RichTextAreaElement, seems that no method is implemented. All code in this class is:
#ServerClass("com.vaadin.ui.RichTextArea")
public class RichTextAreaElement extends AbstractFieldElement {
}
As you can see, no method is declared.
How can I do a test where a user change the value of this rich text area? It is not implemented?
Hmm yeah, that looks like some work in progress, probably because it's a complex component with all the features it provides. Nonetheless we can workaround the limitations a bit, again making use of chrome developer tools (or similar) and some custom classes to select the components by (actually it's just the gwt-RichTextArea).
Of course this serves just as a starting point and can be further enhanced. Also I'd be very interested to see a more elegant solution if someone finds one...
Structure inspection
Test class
public class RichTextAreaTest extends TestBenchTestCase {
#Before
public void setUp() throws Exception {
System.setProperty("webdriver.chrome.driver", "D:\\Kit\\chromedriver_win32\\chromedriver.exe");
setDriver(new ChromeDriver());
}
#After
public void tearDown() throws Exception {
// TODO uncomment below once everything works as expected
//getDriver().quit();
}
#Test
public void shouldModifyRichTextArea() throws InterruptedException {
// class to identify the editor area by
String editorClass = "gwt-RichTextArea";
// open the browser
getDriver().get("http://localhost:8080/");
// select the first rich text
RichTextAreaElement richTextArea = $(RichTextAreaElement.class).first();
// get the editor section which is where we're writing
WebElement richTextEditorArea = richTextArea.findElement(By.className(editorClass));
// click inside to make it "editable"
richTextEditorArea.click();
// send some keystrokes
richTextEditorArea.sendKeys(" + something else added by selenium");
}
}
Result:
Update for getting the value
If you simply want to get the text, the code below will do the trick:
// switch to the editor iframe
getDriver().switchTo().frame(richTextEditorArea);
// get the <body> section where the text is inserted, and print its text
System.out.println("Text =[" + findElement(By.xpath("/html/body")).getText() + "]");
Output
Text =[Some predefined text + something else added by selenium]
At the end, I was able to obtain the content of the element selecting the first iframe of the page, and searching for the body content. The final code looks like:
String currentWindow = getDriver().getWindowHandle();
getDriver().switchTo().frame(getDriver().findElement(By.tagName("iframe")));
WebElement webelement = this.findElement(By.xpath("/html/body"));
String text = webelement.getText();
getDriver().switchTo().window(currentWindow);
return text;
As I need to switch between the iframe and the window, I am only able to obtain the content of the element, not the element itself. If I return directly the element for future use, an org.openqa.selenium.StaleElementReferenceException: Element belongs to a different frame than the current one - switch to its containing frame to use it exception is obtained.
For changing the text, the solutions is very similar, only use the sendKey functions to first remove existing characters and later add the new text:
String currentWindow = getDriver().getWindowHandle();
getDriver().switchTo().frame(getDriver().findElement(By.tagName("iframe")));
WebElement webelement = this.findElement(By.xpath("/html/body"));
// Remove any previous text.
String previousText = webelement.getText();
for (int i = 0; i < previousText.length(); i++) {
webelement.sendKeys(Keys.DELETE);
}
// Set text.
webelement.sendKeys(text);
getDriver().switchTo().window(currentWindow);

JavaFX, change css tablecell on sort

I have to change the styleclass of a TableCell in function of the data displayed, for example: if the value of a cell is the same in two contiguous rows, the cell has to be highlighted (i.e.: background red). This must work both adding data to the table and sorting by any column.
To do so, on sorting, I added a listener to tableview.getSortOrder() and in its onChange method the logic to do what I described above. By example:
public void onChanged(ListChangeListener.Change<? extends TableColumn> change) {
if (change.getList().size() > 0) {
Platform.runLater(new Runnable() {
#Override
public void run() {
/* set some css on tableview cells */
}
});
}
}
The problem is that doing so css changes are applied on the next refresh of the table not immediately. My suspects are on doing this inside Platform.runLater but I need it to have the data sorted as they should be, before changing styles.
Did I do anything wrong? Does exist a better way to do what I described?
You could do that if you have a specific css file for it and add it.
final String css = getClass.getResource("the_css.css").toExternalForm();
and add this in the Platform.runLater:
scene.getStylesheet.add(css);
remove if necessary with:
scene.getStylesheet.remove(css);
Not exactly sure if this does the trick, but it should change the background color right away and not after a refresh. i hope it's helping you in the right direction.

GWT CellList... when item clicked, previously clicked item loses its style

I have GWT CellList and after adding items via a DataProvider I use the following code to add styling to each item.
members... we can styling if a matched item is also in members
matched... passed in as a MetaJsArray<Contact>
CellList<Contact> list = getView().getResults();
for (int i=0; i<matched.length(); i++) {
if (members.isExistingEntry(matched.get(i))) {
list.getRowElement(i).addClassName("RED");
}
}
This code works until... I click items in the list.
onCellPreview() is called for each item clicked, but the previously clicked item loses its "RED" styling.
Do I need to add styling differently? Or how do I stop the loss of "RED"?
My guess its something to do the way GWT generates the javascript. When you manually set the cell on load its all good. When you select it, the javascript changes the object to use the selected CSS and when you un select it, the CSS changes to the default GWT CSS style for the cell.
Only way I can think of is to have a handler on select. When you select an item:
selectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
public void onSelectionChange(SelectionChangeEvent event) {
// get item last selected
// check if needs re styling
// restyle
// do things with the new selected object
}
});
Add another check through the cell list and mark the ones that got unmarked.
This way might be inefficient, but its one way of avoiding your problem that I can think of. hope it helps.
After trying various approaches the only want that works, without hacks, is to define the style at the point of rendering.
With my own ContactCell extending AbstractCell the render() function can pass in a styling value into the contactcell.ui.xml file.
#Override
public void render(Context context, Contact value, SafeHtmlBuilder sb) {
if (value == null) {
return;
}
String styling = value.getStyling();
uiRenderer.render(sb, styling);
}
and then in contactcell.ui.xml file
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui='urn:ui:com.google.gwt.uibinder'>
<ui:with field='styling' type='java.lang.String'/>
<div class="{styling}"> ... </div>
GWT will mangle the style name so define your own CssResource class to access the class name thru so that the class name is mangled throughout the app.

How do you add a row listener to a Flextable in GWT?

How do you add a row listener to a specific row, or all rows in a table? I need to add a type of "onMouseOver" listener to the rows so that when you hover over them, it changes the background color of the row, much like getRowFormatter will allow you to do.
// this is click
final FlexTable myTable = new FlexTable();
myTable.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
Cell cell = myTable.getCellForEvent(event);
int receiverRowIndex = cell.getRowIndex(); // <- here!
}
});
Supposing GWT 1.5.3:
CLICK EVENT HANDLING
If you are using FlexTable and you wanted a click event handler, you could use the FlexTable.addTableListener() and register your own TableListener. The TableListener object will need to implement the onCellClicked callback which would give you the row number.
OTHER EVENTS HANDLING (e.g. HOVER)
If you need to handle other type of events other than click (say, hover), GWT currently doesn't have a ready interface for that. You pretty much left on your own to implement them yourself. There's two ways of doing it that I can think of now:
The quick and dirty way, is probably by exploiting JSNI, which provides a means for you to inject Javascript into your GWT code. I didn't use much JSNI (apart from really hard workarounds which is not worth the effort writing it in pure GWT) in my code so I can't show you an example; but frankly I won't recommend this as it reduces maintainability and extensibility.
If you wanted a native, GWT interface, you can create a new class that inherits HTMLTable or FlexTable. At the constructor, call the sinkEvents function with your needed events. (e.g. for hover, you'll probably need sinkEvents(Event.ONMOUSEOVER)). Then you'll need the onBrowserEvent function that handles the mouseover.
A quick template of how the code should look like:
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.FlexTable;
public class FlexTableWithHoverHandler
extends FlexTable
{
public FlexTableWithHoverHandler()
{
super();
sinkEvents(Event.ONMOUSEOVER);
}
#Override
public void onBrowserEvent(Event event)
{
switch(DOM.eventGetType(event))
{
case Event.ONMOUSEOVER:
// Mouse over handling code here
break;
default:
break;
}
}
}
The best of learning how to code this is by looking at the GWT source code itself (search for sinkEvent) and getting the feel on how to do it the GWT way.
I found it much simple to add javascript directly to the TR element. My code assumes that a widgets DOM parent is a TD and the grandparent is the TR so you need to be sure you know your DOM.
Here's my code. Nice and simple, no JSNI or GWT DOM event management required.
TableRowElement rowElement = (TableRowElement) checkbox.getElement().getParentElement().getParentElement();
rowElement.setAttribute("onMouseOver", "this.className='" + importRecordsResources.css().normalActive() + "'");
rowElement.setAttribute("onMouseOut", "this.className='" + importRecordsResources.css().normal() + "'");
I just did it this simple way:
protected void handleRowsSelectionStyles(ClickEvent event) {
int selectedRowIndex = fieldTable.getCellForEvent(event).getRowIndex();
int rowCount = fieldTable.getRowCount();
for (int row = 0; row < rowCount; row++) {
Element rowElem = fieldTable.getRowFormatter().getElement(row);
rowElem.setClassName(row == selectedRowIndex ? "row selected" : "row");
}
}
You call this method from the cells you want to be clickable
int row = 0;
for (final RowDataProxy rowData : rowDataList) {
Label fieldName = new Label(rowData.name());
fieldName.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
handleRowsSelectionStyles(event);
}
});
fieldTable.setWidget(row++, 0, fieldName);
}
Best Regards,
Zied Hamdi

Resources