Changing colors in xamDataGrid cells - colors

I have xamDataGrid bound to DataTable where first column contains reference values. Coloring of all other columns depends on whether the value in cells is or isn't equal to the value of reference column. The logic uses converter.
What I want to achieve is when I move another column to the 1st position, it will become the reference column and the colors in all other columns should change.
I'm listening to FieldPositionChanged event and invalidating the grid layout, but it does not work:
grid.UpdateLayout();
grid.InvalidateVisual();
The breakpoint in converter is hit but not for all records (only 2 or 3).

If you set the CellValuePresenterStyle when the fields move they should update correctly. The following logic will do this:
void XamDataGrid1_FieldPositionChanged(object sender, Infragistics.Windows.DataPresenter.Events.FieldPositionChangedEventArgs e)
{
FieldLayout layout = e.Field.Owner;
Field first = null;
foreach (Field f in layout.Fields)
{
if (f.ActualPosition.Column == 0)
first = f;
}
if (first != null)
{
SetCellValuePresenterStyle(e.Field.Owner, first);
}
}
void XamDataGrid1_FieldLayoutInitialized(object sender, Infragistics.Windows.DataPresenter.Events.FieldLayoutInitializedEventArgs e)
{
SetCellValuePresenterStyle(e.FieldLayout, e.FieldLayout.Fields[0]);
}
void SetCellValuePresenterStyle(FieldLayout layout, Field sourceField)
{
Binding sourceValueBinding = new Binding("DataItem[" + sourceField.Name + "]");
foreach (Field f in layout.Fields)
{
if (f != sourceField)
{
Style cellValuePresenterStyle = new Style(typeof(CellValuePresenter));
Binding compareValueBinding = new Binding("DataItem[" + f.Name + "]");
MultiBinding styleBinding = new MultiBinding();
styleBinding.Bindings.Add(sourceValueBinding);
styleBinding.Bindings.Add(compareValueBinding);
styleBinding.Converter = new EqualMultiValueConverter();
DataTrigger trigger = new DataTrigger();
trigger.Value = true;
trigger.Binding = styleBinding;
cellValuePresenterStyle.Triggers.Add(trigger);
Setter backgroundSetter = new Setter(Control.BackgroundProperty, Brushes.Green);
trigger.Setters.Add(backgroundSetter);
f.Settings.CellValuePresenterStyle = cellValuePresenterStyle;
}
else
{
f.Settings.CellValuePresenterStyle = null;
}
}
}

Related

Update field for all rows on grid

I am working on recalculating percentage value of each rows when a field value on a row is updated. I have created two custom fields PoundsUsed and PercentOfWIP for INComponentTran DAC. When PoundsUsed is updated I would like to recalculate the PercentOfWIP for all INComponentTran records in Kit Assembly.
I have also created a custom field that is the sum of INComponentTran's PoundsUsed and calculating percentage based on that. Below is the code snippet that I have written to accomplish but it's only updating the latest record.
private decimal CalculateTotalLBSProduced()
{
decimal totalPortions = 0M;
decimal totalLBs = 0M;
foreach (INComponentTran tran in Base.Components.Select())
{
INTranExt tranExt = tran.GetExtension<INTranExt>();
if (tranExt.UsrPoundsUsed.HasValue)
{
if (tran.UOM == "PRTION")
{
totalPortions = totalPortions + tranExt.UsrPoundsUsed.Value;
}
if (tran.UOM == "LB")
{
totalLBs = totalLBs + tranExt.UsrPoundsUsed.Value;
}
}
}
return totalPortions - totalLBs;
}
private void CalculatePercentOfWIP()
{
decimal totalLBSProduced = CalculateTotalLBSProduced();
Base.Document.Cache.SetValueExt<INKitRegisterExt.usrLBSProduced>(Base.Document.Current, totalLBSProduced);
foreach (INComponentTran tran in Base.Components.Select())
{
decimal percentOfWIP = 0M;
Base.Components.Current = tran;
INTranExt tranExt = tran.GetExtension<INTranExt>();
if (tran.UOM == "PRTION")
{
decimal? poundsUsed = tran.GetExtension<INTranExt>().UsrPoundsUsed.GetValueOrDefault();
if (totalLBSProduced != 0 && poundsUsed.HasValue && poundsUsed.Value !=0)
{
percentOfWIP = (poundsUsed.Value / totalLBSProduced) * 100;
}
}
Base.Components.Cache.SetValueExt<INTranExt.usrPercentOfWIP>(tran, percentOfWIP);
}
}
protected void INComponentTran_UsrPoundsUsed_FieldUpdated(PXCache cache, PXFieldUpdatedEventArgs e, PXFieldUpdated InvokeBaseHandler)
{
if (InvokeBaseHandler != null)
InvokeBaseHandler(cache, e);
var row = (INComponentTran)e.Row;
if (row == null) return;
CalculateTotalLBSProduced();
CalculatePercentOfWIP();
}
Thanks.

How can I average the sum of detail field values and put the result in the header

I have a field in the detail / grid section of a custom screen that I want to essentially average (sum divided by row count), and then display this value in the header section. I can't seem to find any examples of how to do this with a PXFormula field. If I need to use the RowSelected event (or FieldUpdating event) then so be it, but I was hoping to do this with the PXFormula field.
I did it this way:
protected virtual void xTACProjectMaster_RowPersisting(PXCache sender, PXRowPersistingEventArgs e)
{
Decimal? totPctComplete = 0;
int rowCount = 0;
var pj = e.Row as xTACProjectMaster;
if (pj != null)
{
PXResultset<xTACProjectTask> res = PXSelect<xTACProjectTask,
Where<xTACProjectTask.projectID, Equal<Required<xTACProjectTask.projectID>>>>.Select(this, pj.ProjectID);
foreach (PXResult<xTACProjectTask> rec in res)
{
xTACProjectTask pt = rec;
totPctComplete += pt.PctComplete;
rowCount++;
}
if(rowCount > 0)
pj.PctComplete = totPctComplete / rowCount;
}
}

Trouble changing background color of row in codename one table

I have an app with a route datatable. The data is csv file. I like
highlight a row in a table in codenameone by changing the backgroundcolor of the row. How can I do this?
My Code is
String File_Name ="/route.csv";
//"/root/sdcard/Pictures/route.csv";
File f= new File (File_Name);
if (f.exists())
InputStream is = Display.getInstance().getResourceAsStream(getClass(), File_Name );
CSVParser parser = new CSVParser();
String[][] data = parser.parse(is);
String[] columnNames = new String[data[0].length];
l = data.length;
for(int iter= 0 ; iter < columnNames.length ; iter++) {
if (iter== 0) {
columnNames[iter] = "Naam";
}
else if (iter== 1) {
columnNames[iter] = "Latitude";
}
else if (iter== 2) {
columnNames[iter] = "Longitude";
}
}
tm = new DefaultTableModel(columnNames, data);
}
}
catch (IOException err){
err.printStackTrace();
}
further in the code
Table tm2 = new Table(tm)
EDIT solved myself
I edited the table definiton tm2 and added the variable A. A is the row which is highlighted
Table tm2 = new Table(tm) {
#Override
public Component createCell(Object value, int row, int column, boolean editable) { // (1)
Component cell;
cell = super.createCell(value, row, column, editable);
if(row > a-1 && row < a+1) { // (5)
// pinstripe effect
cell.getAllStyles().setBgColor(0xe2f30d);
cell.getAllStyles().setBgTransparency(255);
}
return cell;
}
Changing the cell color is discussed in the developer guide as you probably discovered the pinstripe sample from there.
The full sample from the developer guide is this:
Table table = new Table(model) {
#Override
protected Component createCell(Object value, int row, int column, boolean editable) {
Component cell;
if(row == 1 && column == 1) {
Picker p = new Picker();
p.setType(Display.PICKER_TYPE_STRINGS);
p.setStrings("Row B can now stretch", "This is a good value", "So Is This", "Better than text field");
p.setSelectedString((String)value);
p.setUIID("TableCell");
p.addActionListener((e) -> getModel().setValueAt(row, column, p.getSelectedString()));
cell = p;
} else {
cell = super.createCell(value, row, column, editable);
}
if(row > -1 && row % 2 == 0) {
// pinstripe effect
cell.getAllStyles().setBgColor(0xeeeeee);
cell.getAllStyles().setBgTransparency(255);
}
return cell;
}
#Override
protected TableLayout.Constraint createCellConstraint(Object value, int row, int column) {
TableLayout.Constraint con = super.createCellConstraint(value, row, column);
if(row == 1 && column == 1) {
con.setHorizontalSpan(2);
}
con.setWidthPercentage(33);
return con;
}
};

How to edit data with dynamic TableView with dynamic column in JAVAFX

Today This is the demo to show data from CSV for DAT file without make custom class on tableView in JavaFX 2.0. I call this TableView as Dynamic TableView because the tableview automatically manages the columns and rows.
On my research about the editable on tableView we must have a custom class and implement it to tableView to show as this demo ==> http://docs.oracle.com/javafx/2/ui_controls/table-view.htm
But in this case I can not do it because we don't know how many column example with csv file or .dat file.... I want to do editable on this tableView in this case by add TextField into TableCell. How does it do without make custom class (because you do not how many column ...), and if it must make custom class then how about the design of custom class for this case?
Could you please help me?
private void getDataDetailWithDynamic() {
tblView.getItems().clear();
tblView.getColumns().clear();
tblView.setPlaceholder(new Label("Loading..."));
// #Override
try {
File aFile = new File(txtFilePath.getText());
InputStream is = new BufferedInputStream(new FileInputStream(aFile));
Reader reader = new InputStreamReader(is, "UTF-8");
BufferedReader in = new BufferedReader(reader);
final String headerLine = in.readLine();
final String[] headerValues = headerLine.split("\t");
for (int column = 0; column < headerValues.length; column++) {
tblView.getColumns().add(
createColumn(column, headerValues[column]));
}
// Data:
String dataLine;
while ((dataLine = in.readLine()) != null) {
final String[] dataValues = dataLine.split("\t");
// Add additional columns if necessary:
for (int columnIndex = tblView.getColumns().size(); columnIndex < dataValues.length; columnIndex++) {
tblView.getColumns().add(createColumn(columnIndex, ""));
}
// Add data to table:
ObservableList<StringProperty> data = FXCollections
.observableArrayList();
for (String value : dataValues) {
data.add(new SimpleStringProperty(value));
}
tblView.getItems().add(data);
}
} catch (Exception ex) {
System.out.println("ex: " + ex.toString());
}
for(int i=0; i<tblView.getColumns().size(); i++) {
TableColumn col = (TableColumn)tblView.getColumns().get(i);
col.setPrefWidth(70);
}
}
private TableColumn createColumn(
final int columnIndex, String columnTitle) {
TableColumn column = new TableColumn(DefaultVars.BLANK_CHARACTER);
String title;
if (columnTitle == null || columnTitle.trim().length() == 0) {
title = "Column " + (columnIndex + 1);
} else {
title = columnTitle;
}
Callback<TableColumn, TableCell> cellFactory = new Callback<TableColumn, TableCell>() {
#Override
public TableCell call(TableColumn p) {
System.out.println("event cell");
EditingCellData cellExtend = new EditingCellData();
return cellExtend;
}
};
column.setText(title);
column.setCellValueFactory(cellFactory);
return column;
}
Thanks for your reading.
This is the best way to resolve it ==> https://forums.oracle.com/message/11216643#11216643
I'm really thank for your reading about that.
Thanks

How to create multiple checkbox in canvas

I get trouble when I try to create a check box in canvas.
My checkbox works well but I don't know how to store value of each item, that mean when user check row 1 , and then they move to another row check box still check row 1, and when user check row 1 and 2 and move to another row, check box will check row 1 and 2.
But I can't find out solution for this problem
modify your code to use selectTodelete as boolean array instead of int, about like shown below
// ...initialization of DataList
boolean[] selectTodelete = new boolean[2]; // instead of int
{ selectTodelete[0] = selectTodelete[1] = false; } // init array
Command editCommand, backCommand,selectCmd, unselectCmd,selectAll;
//...
protected void paint(Graphics g) {
//...
for(int i =0 ; i<countRow; i++ ){
//draw background
//...
if(selectTodelete[i]){ // was selectTodelete == 1
//draw select dot at location for row 'i'
//...
}
// remove: you don't need that anymore: if(selectTodelete == 2) {
//draw select dot...
//}
// draw a checkbox before each item
// ...
}
}
public void commandAction(Command c, Displayable d) {
//...
if(c == selectCmd){
selectTodelete[selectedItem] = true;
}
if(c== unselectCmd){
selectTodelete[selectedItem] = false;
}
if(c == selectAll){
selectTodelete[0] = selectTodelete[1] = true;
}
repaint();
}
//...
}
update - answer to question in comments
I want to get RCID fit to checked it mean when row was checked I can get this id and when I use delete command it will delete all rows were checked
For that, you can expose selectTodelete for use outside of its class with getter, or, better yet, with method like below...
boolean isSelected(int elementNum) {
return elementNum >= 0 && elementNum < selectTodelete.length
&& selectTodelete[elementNum];
} // modelled after javax.microedition.lcdui.Choice.isSelected
...information exposed like that can be further used anywhere when you need it to deal with RCID, like eg in method below:
Vector useSelection(DataList dataList, DataStore[][] ds) {
Vector result = new Vector();
int count = ds.length;
for(int i = 0; i < count; i++ ) {
if (!dataList.isSelected(i)) {
continue; // skip non selected
}
System.out.println("RCID selected: [" + ds[i][5].cellText + "]");
result.addElement(ds[i][5]);
}
return result;
}

Resources