My requirement is to use 2 tables and 1 chart to visualize my data set. Each data element contains its (unique) name and a bunch of data belonging to it. The first table will show the name of every dataset I have and the second table will show the data belonging to the dataset (row) being selected in the first table. The second table and the chart will show the same data and both belong to the dataset (row) being selected in the first table. I have achieved half of this behavior (linking both table) now by using the code below.
The problem I currently have now is: I can't figure out the way to let the chart display the same data as the second table. My idea is to set the chart data in the ChangeListener, but the problem is the data model of the table is likely to not suitable with the chart. I have the readingData field as ObservableList in the TableDataModel class which is the type that the chart accept but it is an ObservableList of ReadingData not XYChart.Data. Is there any way I can use the XYChart.Data in the ReadData class?
My main class:
ObservableList<TableDataModel> tableData = FXCollections.observableArrayList();
// Other code omitted
/* Create the first table */
TableView<TableDataModel> myTable = new TableView<TableDataModel>();
TableColumn nameColumn = new TableColumn("Name");
nameColumn.setCellValueFactory(new PropertyValueFactory<TableDataModel, String>("name"));
// Other column omitted
myTable.setItems(tableData);
myTable.getColumns().addAll(nameColumn, ...);
// When user select on any row update the second table items
myTable.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<TableDataModel>()
{
#Override
public void changed(ObservableValue<? extends TableDataModel> arg0, TableDataModel arg1, TableDataModel arg2)
{
dataTable.setItems(arg2.readingData);
}
});
/* The second table */
TableView<ReadData> dataTable = new TableView<ReadData>();
TableColumn valueColumn = new TableColumn("Value");
valueColumn.setCellValueFactory(new PropertyValueFactory<ReadData, Integer>("value"));
// Other column omitted
dataTable.setItems(null);
dataTable.getColumns().addAll(valueColumn, ...);
TableDataModel.java:
private final SimpleStringProperty name;
// Other SimpleStringProperty and its get and set method omitted
public final ObservableList<ReadData> readingData = FXCollections.observableArrayList();
ReadData.java:
// I use XYChart.Data here because I think that this might be useful when I want to show this on the chart
private SimpleObjectProperty<XYChart.Data<Integer, Integer>> value;
// Other property
// Provide this to make below line work
// valueColumn.setCellValueFactory(new PropertyValueFactory<ReadData, Integer>("value"));
public int getValue()
{
return value.get().getYValue();
}
AFAIK you need to put your XYChart.Datas into the XYChart.Series first, then put that series into the chart by chart.getData().add(series). I think you can do this in your myTable selected change listener: Create there a new series (or modify existing, previously created and added one), add all your value.get() values from the ReadData. See the example of LineChart.
Related
I have the following problem: I try to populate a tableview in JavaFX8 with an array. So, I try to add the array as a row to the tableview. I run this code in the Controller of my FXML file, when enter is pressed. This is the code:
String[] words = {"ace", "boom", "crew", "dog", "eon"};
List<String> tableViewRow = Arrays.asList(words);
ObservableList<String> row = FXCollections.observableList(tableViewRow); //observableArrayList also doesn't work
transactionOverview.getItems().add(row);
transactionOverview is my tableview, and the String[] is just a placeholder for my actual String[]. I tried to create my tableview in multiple ways:
public TableView<ObservableList<String>> transactionOverview;
public TableView<ObservableList> transactionOverview;
public TableView transactionOverview;
None of them works.
The problem is that tableview gets an extra row, which I can select, but there are now string values visible in the tableview. I don't know if they are added.
My code is based on Javafx 2.2 - Dynamic table view - table data (answer from Jitendra Pareek), and I have chosen for this solution because I don't want to use an extra class to populate my tableview.
Any help is appreciated!
Since (according to your comments) you have a fixed number of columns, I would strongly recommend creating a model class to hold the items in each row of the table. You can then follow the standard patterns and it should work readily.
However you manage a TableView, you must provide a cell value factory for each column. This is essentially a function that specifies how to get the value for a cell from the item in the row. If your use a model class that uses JavaFX properties, then you can use a PropertyValueFactory (though Java 8 lambda expressions make that pretty much redundant). Otherwise, you need to implement a callback.
If you really want to use a list structure to hold the data for each row, and assuming your table and table columns are all defined in the FXML file, you would do something like this in your controller class:
#FXML
private TableView<ObservableList<String>> transactionOverview ;
// ...
public void initialize() {
for (int i=0; i < transactionOverview.getColumns().size(); i++) {
TableColumn<ObservableList<String>, String> col = transactionOverview.getColumns().get(i);
final int colIndex = i ;
col.setCellValueFactory( (CellDataFeatures cellData) -> {
ObservableList<String> rowData = cellData.getValue();
return new ReadOnlyStringWrapper(rowData.get(colIndex));
});
}
// ...
}
I am using JQGrid with the Trirand.Web.Mvc class, and trying to figure out how to do custom paging.
I have seen the paging demos here
The problem with these demos is that they bind directly to a linq context object and lets MVC take care of the paging.
// This method is called when the grid requests data. You can choose any method to call
// by setting the JQGrid.DataUrl property
public JsonResult PerformanceLinq_DataRequested()
{
// Get both the grid Model and the data Model
// The data model in our case is an autogenerated linq2sql database based on Northwind.
var gridModel = new OrdersJqGridModel();
var northWindModel = new NorthwindDataContext();
// return the result of the DataBind method, passing the datasource as a parameter
// jqGrid for ASP.NET MVC automatically takes care of paging, sorting, filtering/searching, etc
return gridModel.OrdersGrid.DataBind(northWindModel.OrdersLarges);
}
The data set I want to bind to is quite complex and I am returning it from a stored procedure, which does the paging for me.
So all I have to give JQGrid is the correct size of rows for a specific page of the entire resultset. I can also return the total row count.
So I have my results in a List myListOfObjects.
I can pass this into the DataBind using myListOfObjects.AsQueryable()
The problem is, JQGrid thinks there is only {page size} rows, so does not display any of the paging options.
Is it possible to pass in the total row count?
Other grids, like Teleriks MVC grid allows you to pass in the Total row count, and it displays the paging correctly
Ok, so I've managed to solve this myself. There may be other ways to do it, if so I'd love to hear them!
The JQGrid.DataBind produces an JsonResult object, whose Data value is set to Trirands own object Trirand.Web.Mvc.JsonResponse
It's an internal class to their Trirand.Web.Mvc, so i had to copy its structure which I could see using Visual Studio debugging.
It has:
page - the current page number
records - the total record count
rows - of type Trirand.Web.Mvc.JsonRow (which I need to replicate too)
total - the total number of pages needed
JsonRow looks like:
cell - a string array of your columns
id - your row ID
So my code looked like this:
var jsonList = new List<JSONRow>();
myData.ForEach(x => jsonList.Add(new JSONRow(x)));
var jsonResult = Json (new
{
page = page,
rows = jsonList.ToArray(),
records = totalRows,
total = Math.Round((double)totalRows / rows, MidpointRounding.AwayFromZero)
}, JsonRequestBehavior.AllowGet);
return jsonResult;
My JsonRow looks like this:
public class JSONRow
{
public string[] cell { get; set; }
public string id { get; set; }
public JSONRow(MyObjectType myObject)
{
id = myObject.id;
cell = new string[3];
cell[0] = myObject.Col1;
cell[1] = myObject.Col2?? "";
cell[2] = myObject.Col3?? "";
}
}
I have a form with a combobox/drop down to select the user language. If the user changes the language, I'd like to update all the labels but leave the input elements alone.
In jQuery, I'd request a list of label IDs and the new texts via JSON and then use a loop like this:
var texts = {[ {id:'nameLabel', text:'First Name'}, {id:'familyLabel', text:'Family Name'} ]};
for( var i=0; i<texts.length; i++) {
var item = texts[i];
$('#'+item.id).text(item.text);
}
That would update all the labels without modifying anything else. How do I do this in Wicket?
[EDIT] What I tried:
DropDownChoice<Locale> ddc = new DropDownChoice<Locale>(...);
ddc.add( new AjaxFormComponentUpdatingBehavior("onchange") {
private static final long serialVersionUID = 1L;
#Override
protected void onUpdate( AjaxRequestTarget target ) {
getSession().setLocale( language );
for( MarkupContainer label : labels ) {
target.addComponent( label );
}
}
});
This does change the labels but it also renders all the input fields again. I found no way to access the current values of the input fields.
[EDIT2] The list of labels is created like so:
StringResourceModel usernameLabel = new StringResourceModel("usernameLabel", this, new Model<ValueMap>(map));
labels.add(add(new Label("usernameLabel", usernameLabel)));
This is wrong:
labels.add(add(new Label("usernameLabel", usernameLabel)));
You're not adding Label instances to 'labels', it's repeatedly adding the container you are adding it to (probably the Page instance). The method 'add()' doesn't return the component being added, it returns the container you are adding the components into.
Try changing it to:
Label label = new Label("usernameLabel", usernameLabel);
add(label);
labels.add(label);
The functionality I am trying to use is:
- Create a ObjectDataSource for selection and updating controls on a web page (User Control).
- Use the DataObjectTypeName to have an object created that would send the data to an UpdateMethod.
- Before the values are populated in the DataObjectTypeName’s object, I would like to pre-populate the object so the unused items in the class are not defaulted to zeros and empty strings without me knowing whether the zero or default string was set by the user or by the application.
I cannot find a way to pre-populate the values (this was an issue back in 2006 with framework 2.0). One might ask “Why would anyone need to pre-populate the object?”. The simple answer is: I want to be able to randomly place controls on different User Controls and not have to be concerned with which UpdateMethod needs to handle which fields of an object.
For Example, let’s say I have a class (that reflects a SQL Table) that includes the fields: FirstName, LastName, Address, City, State, Zip. I may want to give the user the option to change the FirstName and LastName and not even see the Address, City, State, Zip (or vice-versa). I do not want to create two UpdateMethods where one handled FirstName and LastName and the other method handles the other fields. I am working with a Class of some 40+ columns from multiple tables and I may want some fields on one screen and not another and decide later to change those fields from one screen to another (which breaks my UpdateMethods without me knowing).
I hope I explained my issue well enough.
Thanks
This is hardly a solution to the problem, but it's my best stab at it.
I have a GridView with its DataSourceID set to an ObjectDataSource.
Whenever a row is updated, I want the property values in the object to be selectively updated - that is - only updated if they appear as columns in the GridView.
I've created the following extension:
public static class GridViewExtensions
{
public static void EnableLimitUpdateToGridViewColumns(this GridView gridView)
{
_gridView = gridView;
if (_gridView.DataSourceObject != null)
{
((ObjectDataSource)_gridView.DataSourceObject)
.Updating += new ObjectDataSourceMethodEventHandler(objectDataSource_Updating);
}
}
private static GridView _gridView;
private static void objectDataSource_Updating(object sender, ObjectDataSourceMethodEventArgs e)
{
var newObject = ((object)e.InputParameters[0]);
var oldObjects = ((ObjectDataSource)_gridView.DataSourceObject).Select().Cast<object>();
Type type = oldObjects.First().GetType();
object oldObject = null;
foreach (var obj in oldObjects)
{
if (type.GetProperty(_gridView.DataKeyNames.First()).GetValue(obj, null).ToString() ==
type.GetProperty(_gridView.DataKeyNames.First()).GetValue(newObject, null).ToString())
{
oldObject = obj;
break;
}
}
if (oldObject == null) return;
var dynamicColumns = _gridView.Columns.OfType<DynamicField>();
foreach (var property in type.GetProperties())
{
if (dynamicColumns.Where(c => c.DataField == property.Name).Count() == 0)
{
property.SetValue(newObject, property.GetValue(oldObject, null), null);
}
}
}
}
And in the Page_Init event of my page, I apply it to the GridView, like so:
protected void Page_Init()
{
GridView1.EnableLimitUpdateToGridViewColumns();
}
This is working well for me at the moment.
You could probably apply similar logic to other controls, e.g. ListView or DetailsView.
I'm currently scratching my head to think of a way this can be done in a rendering-agnostic manner - i.e. without having to know about the rendering control being used.
I hope this ends up as a normal feature of the GridView or ObjectDataSource control rather than having to hack it.
After going through Entity Framework I have a couple of questions on implementing auditing in Entity Framework.
I want to store each column values that is created or updated to a different audit table.
Right now I am calling SaveChanges(false) to save the records in the DB(still the changes in context is not reset). Then get the added | modified records and loop through the GetObjectStateEntries. But don't know how to get the values of the columns where their values are filled by stored proc. ie, createdate, modifieddate etc.
Below is the sample code I am working on it.
// Get the changed entires( ie, records)
IEnumerable<ObjectStateEntry> changes = context.ObjectStateManager.GetObjectStateEntries(EntityState.Modified);
// Iterate each ObjectStateEntry( for each record in the update/modified collection)
foreach (ObjectStateEntry entry in changes)
{
// Iterate the columns in each record and get thier old and new value respectively
foreach (var columnName in entry.GetModifiedProperties())
{
string oldValue = entry.OriginalValues[columnName].ToString();
string newValue = entry.CurrentValues[columnName].ToString();
// Do Some Auditing by sending entityname, columnname, oldvalue, newvalue
}
}
changes = context.ObjectStateManager.GetObjectStateEntries(EntityState.Added);
foreach (ObjectStateEntry entry in changes)
{
if (entry.IsRelationship) continue;
var columnNames = (from p in entry.EntitySet.ElementType.Members
select p.Name).ToList();
foreach (var columnName in columnNames)
{
string newValue = entry.CurrentValues[columnName].ToString();
// Do Some Auditing by sending entityname, columnname, value
}
}
Here you have two basic options:
Do it at the database level
Do it in the c# code
Doing it at the data base level, means using triggers. In that case there is no difference if you are using enterprise library or another data access technology.
To do it in the C# code you would add a log table to your datamodel, and write the changes to the log table. When you do a save changes both the changes to the data and the information which you wrote to the log table would be saved.
Are you inserting the new record using a stored proc? If not (i.e. you are newing up an object, setting values, inserting on submit and then saving changes the new object id will be automatically loaded into the id property of the object you created. If you are using a stored proc to do the insert then you need to return the ##IDENTITY from the proc as a return value.
EX:
StoreDateContext db = new StoreDataContext(connString);
Product p = new Product();
p.Name = "Hello Kitty Back Scratcher";
p.CategoryId = 5;
db.Products.Add(p);
try
{
db.SaveChanges();
//p.Id is now set
return p.Id;
}
finally
{
db.Dispose;
}