I have an intermediate table that gets information from two other tables from the database (it gets their id), I'd like to show information of the other tables through that intermediate table in each of the others but it show me all of the information.
public showTheatreForm(Resources res, Theatre t) {
Toolbar tb=new Toolbar(true);
current=this;
setToolbar(tb);
getTitleArea().setUIID("Container");
setTitle("modifier actor");
getContentPane().setScrollVisible(false);
super.addSideMenu(res);
Label name = new Label((t.getName()));
Picker datePicker = new Picker();
datePicker.setDate(t.getRdate());
String datestring=(new SimpleDateFormat("yyyy-MM-dd")).format(datePicker.getDate());
Label date = new Label((datestring));
TextField description = new TextField((t.getDescription()));
TextField actors = new TextField((t.getTactor()));
//Label image = new Label((t.getImage()), "Image");
ImageViewer imavu;
try {
imavu = new ImageViewer(getImageFromServer(t.getImage()));
}
catch(Exception e) {
System.out.println(t.getImage());
imavu = new ImageViewer(res.getImage("s.png"));
}
description.setSingleLineTextArea(false);
actors.setSingleLineTextArea(false);
name.setUIID("NewsCenterLine");
date.setUIID("NewsCenterLine");
description.setUIID("NewsCenterLine");
imavu.setUIID("NewsCenterLine");
actors.setUIID("NewsCenterLine");
Label a = new Label("");
Label e = new Label ();
Container content = BoxLayout.encloseY(
e,a, (name),
createLineSeparator(), (actors),
createLineSeparator(),date,
createLineSeparator(), (description),
createLineSeparator(), (imavu)
);
add(content);
show();
}
And this is how I get it from the database:
public ArrayList<Theatre> ShowTheatre (){
ArrayList<Theatre> result=new ArrayList<>();
String url=Statics.BASE_URL+"/theatre/displayTheatre";
req.setUrl(url);
req.addResponseListener(new ActionListener<NetworkEvent>() {
#Override
public void actionPerformed(NetworkEvent evt) {
JSONParser Jsonp;
Jsonp=new JSONParser();
try{
Map<String,Object>mapTheatre= Jsonp.parseJSON(new CharArrayReader(new String(req.getResponseData()).toCharArray()));
List<Map<String,Object>> listofMaps = (List<Map<String,Object>>) mapTheatre.get("root");
for(Map<String,Object> obj : listofMaps)
{
Theatre th=new Theatre();
float id=Float.parseFloat(obj.get("id").toString());
String name=obj.get("name").toString();
String genre=obj.get("genre").toString();
String description=obj.get("description").toString();
String image=obj.get("image").toString();
String trailer=obj.get("trailer").toString();
String poster=obj.get("poster").toString();
String get=obj.get("theatreActors").toString();
th.setId((long)id);
th.setName(name);
th.setTactor(get);
System.out.println(get);
th.setDescription(description);
th.setImage(image);
th.setTrailer(trailer);
th.setPoster(poster);
th.setGenre(genre);
Map<String, Object> dd = (Map<String, Object>) obj.get("rdate");
float ll = Float.parseFloat(dd.get("timestamp").toString());
th.setRdate(new Date(((long) ll * 1000)));
}
result.add(th);
}
} catch (IOException ex) {
System.out.println(
"good");
}
}
});
NetworkManager.getInstance().addToQueueAndWait(req);
return result;
}
Result of the code
This is the result, but I only want to get the "name" and "date" or "description" from the intermediate table
My intermediate table
(the name of the table is theatreActors)
I've got 3 Tables in Vaadin:
My Problem now is that Drag & Drop doesn't work. My Code is the following one:
#Theme("valo")
#SpringView(name = TaskboardView.VIEW_NAME)
public class TaskboardView extends VerticalLayout implements View {
private enum TableType {
DONE, PROGRESS, OPEN;
}
private static final long serialVersionUID = 1L;
private final Logger logger = LoggerFactory.getLogger(TaskboardView.class);
public static final String VIEW_NAME = "taskboard";
// Components:
private SprintController sprintController = new SprintController();
private TaskController taskController = new TaskController();
private Sprint sprint;
private Set<Task> allTasks;
private List<Task> openTasks = new ArrayList<Task>();
private List<Task> inProgressTasks = new ArrayList<Task>();
private List<Task> doneTasks = new ArrayList<Task>();
// UI Components:
private Table openTable = new Table("Open Tasks:");
private int openTableId = 1;
private Table inProgressTable = new Table("Tasks in Progress");
private int inProgressTableId = 1;
private Table doneTable = new Table("Done Tasks");
private int doneTableId = 1;
private TextField sprintName = new TextField();
private OpenTableDropHandler openTableDropHandler = new OpenTableDropHandler();
private InProgressTableDropHandler inProgressTableDropHandler = new InProgressTableDropHandler();
DoneTableHandler doneTableHandler = new DoneTableHandler();
#PostConstruct
void init() {
logger.info("Initializing Taskboard View...");
try {
this.sprint = sprintController.getActiveSprint();
this.allTasks = sprintController.getTasksInSprint(this.sprint.getId().intValue());
sortSprintTasks(this.allTasks);
this.sprintName.setNullRepresentation("-- No active Sprint found --");
this.sprintName.setValue(this.sprint.getSprintName());
this.sprintName.setWidth("800px");
this.sprintName.setReadOnly(true);
this.sprintName.addStyleName("align-center"); // sets Allignment of
// the textfield!!!
} catch (NoActiveSprintReceivedException | NoSprintsExistException | IOException e) {
logger.error("Something went wrong initializing active Sprint. The taskboard can't be displayed.", e);
Notification.show("No Active Sprint found!", Notification.Type.ERROR_MESSAGE);
e.printStackTrace();
return;
} catch (TaskCanNotBeAllocatedException e) {
logger.error("Task of sprint couldn't be allocated to an status.", e);
Notification.show("Error! \n \n Task of sprint couldn't be allocated to an status.",
Notification.Type.ERROR_MESSAGE);
e.printStackTrace();
return;
}
// Layout for Sprint Name:
VerticalLayout headLayout = new VerticalLayout();
headLayout.setSpacing(true);
headLayout.setSizeFull();
;
headLayout.setMargin(true);
headLayout.addComponent(this.sprintName);
headLayout.setComponentAlignment(this.sprintName, Alignment.MIDDLE_CENTER);
setSizeFull();
setSpacing(true);
setMargin(true);
// Layout:
VerticalLayout verticalLayout = new VerticalLayout();
verticalLayout.setSpacing(true);
// Layout for Board:
HorizontalLayout taskBoardLayout = new HorizontalLayout();
taskBoardLayout.setSizeUndefined();
taskBoardLayout.setSpacing(true);
taskBoardLayout.setMargin(true);
// Adding to HorizontalLayout(TaskBoadLayout)
try {
initTable(this.openTable, TableType.OPEN);
initTable(this.inProgressTable, TableType.PROGRESS);
initTable(this.doneTable, TableType.DONE);
} catch (IOException e) {
logger.error("Something went wrong initizalizing Tables.");
Notification.show("Error! \n \n Couldn't initialize tables.", Notification.Type.ERROR_MESSAGE);
return;
}
taskBoardLayout.addComponent(openTable);
taskBoardLayout.addComponent(inProgressTable);
taskBoardLayout.addComponent(doneTable);
// Adding to VerticalLayout (MainLayout)
verticalLayout.addComponent(headLayout);
verticalLayout.addComponent(taskBoardLayout);
verticalLayout.setComponentAlignment(taskBoardLayout, Alignment.MIDDLE_CENTER);
addComponent(verticalLayout);
}
/**
* Sorts the tasks of the sprint to the required lists like open, in
* Progress, done.
*
* #param tasks
* #throws TaskCanNotBeAllocatedException
*/
private void sortSprintTasks(Set<Task> tasks) throws TaskCanNotBeAllocatedException {
logger.info("sortSprintTask(Set<Task>tasks): Sorting Tasks to the required lists...");
for (Task t : tasks) {
logger.info("Checking Sprint Status of Task >>>> " + t.getHeadLine() + " <<<<");
logger.info("Status: " + t.getStatus());
if (t.getStatus().equals(WorkflowStatusConfigurator.open)) {
this.openTasks.add(t);
} else if (t.getStatus().equals(WorkflowStatusConfigurator.inProgress)) {
this.inProgressTasks.add(t);
} else if (t.getStatus().equals(WorkflowStatusConfigurator.done)) {
this.doneTasks.add(t);
} else {
throw new TaskCanNotBeAllocatedException(
"Task can't be allocated to a sprint status: " + WorkflowStatusConfigurator.open + ", "
+ WorkflowStatusConfigurator.inProgress + ", " + WorkflowStatusConfigurator.done + ".");
}
}
}
#Override
public void enter(ViewChangeEvent event) {
// TODO Auto-generated method stub
}
/**
* Creates the tables depending on the type parameter
*
* #param table
* #param type
* #throws IOException
* #throws ClientProtocolException
*/
private void initTable(Table table, TableType type) throws ClientProtocolException, IOException {
table.setSelectable(true);
table.setImmediate(true);
table.setDragMode(TableDragMode.ROW);
table.addContainerProperty("ID", Long.class, null);
table.setColumnWidth("ID", 50);
table.addContainerProperty("Headline", String.class, null);
table.setColumnWidth("Headline", 300);
table.addContainerProperty("Task-Type", String.class, null);
table.setColumnWidth("Task-Type", 120);
table.addContainerProperty("Assignee", String.class, null);
table.setColumnWidth("Assignee", 100);
if (type.equals(TableType.OPEN) && this.openTasks.size() > 0) {
logger.info("Loading values of Open Tasks Table...");
table.setDropHandler(this.openTableDropHandler);
for (Task t : this.openTasks) {
String assignee = this.taskController.getAssigneeInTask(t.getId().intValue()).getUserName();
table.addItem(new Object[] { t.getId(), t.getHeadLine(), t.getTaskType(), assignee }, this.openTableId);
this.openTableId++;
}
return;
}
if (type.equals(TableType.PROGRESS) && this.inProgressTasks.size() > 0) {
logger.info("Loading values of Progress Tasks Table...");
table.setDropHandler(this.inProgressTableDropHandler);
for (Task t : this.inProgressTasks) {
String assignee = this.taskController.getAssigneeInTask(t.getId().intValue()).getUserName();
table.addItem(new Object[] { t.getId(), t.getHeadLine(), t.getTaskType(), assignee }, this.inProgressTableId);
this.inProgressTableId++;
}
return;
}
if (type.equals(TableType.DONE) && this.doneTasks.size() > 0) {
logger.info("Loading values of Done Tasks Table...");
table.setDropHandler(this.doneTableHandler);
for (Task t : this.doneTasks) {
String assignee = this.taskController.getAssigneeInTask(t.getId().intValue()).getUserName();
table.addItem(new Object[] { t.getId(), t.getHeadLine(), t.getTaskType(), assignee }, this.doneTableId);
this.doneTableId++;
}
return;
}
}
private int giveEncreasedAvailableTableId(TableType tableType) {
if(tableType.equals(TableType.OPEN)){
this.openTableId++;
return this.openTableId;
}else if(tableType.equals(TableType.PROGRESS)){
this.inProgressTableId++;
return this.inProgressTableId;
}else if(tableType.equals(TableType.DONE)){
this.doneTableId++;
return this.doneTableId;
}else{
return -1;
}
}
private class OpenTableDropHandler implements DropHandler{
private static final long serialVersionUID = 1L;
private final Logger logger = LoggerFactory.getLogger(OpenTableDropHandler.class);
#Override
public void drop(DragAndDropEvent event) {
// Wrapper for the object that is dragged
logger.info("Received Drag and Drop Event from OpenTable...");
DataBoundTransferable t = (DataBoundTransferable) event.getTransferable();
AbstractSelectTargetDetails dropData = ((AbstractSelectTargetDetails) event.getTargetDetails());
Object itemId = t.getItemId();
Long id = (Long) t.getSourceContainer().getItem(itemId).getItemProperty("ID").getValue();
try {
Task taskToAdd = taskController.getById(id.intValue());
String author = taskController.getAuthorInTask(taskToAdd.getId().intValue()).getUserName();
if ( t.getSourceComponent() != openTable && dropData.getTarget().equals(inProgressTable)) {
logger.info("Preparing Task Update to InProgress...");
openTable.addItem(new Object[] { taskToAdd.getId(), taskToAdd.getHeadLine(),
taskToAdd.getTaskType(), author, taskToAdd.getStatus() }, giveEncreasedAvailableTableId(TableType.OPEN));
openTasks.add(taskToAdd);
inProgressTable.removeItem(itemId);
inProgressTasks.remove(taskToAdd);
}else if(t.getSourceComponent() != openTable && dropData.getTarget().equals(doneTable)){
logger.info("Preparing Task Update to Done...");
openTable.addItem(new Object[] { taskToAdd.getId(), taskToAdd.getHeadLine(),
taskToAdd.getTaskType(), author, taskToAdd.getStatus() }, giveEncreasedAvailableTableId(TableType.OPEN));
openTasks.add(taskToAdd);
doneTable.removeItem(itemId);
doneTasks.remove(taskToAdd);
}else{
logger.info("Do nothing...");
return;
}
taskToAdd.setStatus(WorkflowStatusConfigurator.open);
logger.info("Sending updates of taskboard to webservice...");
HttpResponse response = taskController.put(taskToAdd, taskToAdd.getId().intValue());
MainView.navigator.navigateTo(TaskboardView.VIEW_NAME);
// HttpResponse authorResponse = taskController.setAuthorInTask(taskToAdd.getAuthor().getId().intValue(),
// taskToAdd.getId().intValue());
// HttpResponse assigneeResponse = taskController.setAssigneeInTask(taskToAdd.getAssignee().getId().intValue(),
// taskToAdd.getId().intValue());
} catch (ClientProtocolException e) {
logger.warn("Something went wrong during Drag and Drop Process", e.getCause());
} catch (IOException e) {
logger.warn("Something went wrong during Drag and Drop Process", e.getCause());
}
}
#Override
public AcceptCriterion getAcceptCriterion() {
return AcceptAll.get();
}
}
private class InProgressTableDropHandler implements DropHandler{
private static final long serialVersionUID = 1L;
private final Logger logger = LoggerFactory.getLogger(InProgressTableDropHandler.class);
#Override
public void drop(DragAndDropEvent event) {
// Wrapper for the object that is dragged
logger.info("Received Drag and Drop Event from In Progress Table.");
DataBoundTransferable t = (DataBoundTransferable) event.getTransferable();
AbstractSelectTargetDetails dropData = ((AbstractSelectTargetDetails) event.getTargetDetails());
Object itemId = t.getItemId();
Long id = (Long) t.getSourceContainer().getItem(itemId).getItemProperty("ID").getValue();
try {
Task taskToAdd = taskController.getById(id.intValue());
String author = taskController.getAuthorInTask(taskToAdd.getId().intValue()).getUserName();
if (t.getSourceComponent() != inProgressTable && dropData.getTarget().equals(doneTable) ){
inProgressTable.addItem(new Object[] { taskToAdd.getId(), taskToAdd.getHeadLine(),
taskToAdd.getTaskType(), author, taskToAdd.getStatus() }, giveEncreasedAvailableTableId(TableType.PROGRESS));
doneTable.removeItem(itemId);
inProgressTasks.add(taskToAdd);
doneTasks.remove(taskToAdd);
}else if(t.getSourceComponent() != inProgressTable && dropData.getTarget().equals(openTable)){
inProgressTable.addItem(new Object[] { taskToAdd.getId(), taskToAdd.getHeadLine(),
taskToAdd.getTaskType(), author, taskToAdd.getStatus() }, giveEncreasedAvailableTableId(TableType.PROGRESS));
openTable.removeItem(itemId);
inProgressTasks.add(taskToAdd);
openTasks.remove(taskToAdd);
}else{
return;
}
logger.info("Sending updates of taskboard to webservice...");
taskToAdd.setStatus(WorkflowStatusConfigurator.inProgress);
HttpResponse response = taskController.put(taskToAdd, taskToAdd.getId().intValue());
MainView.navigator.navigateTo(TaskboardView.VIEW_NAME);
}catch (ClientProtocolException e) {
logger.warn("Something went wrong during Drag and Drop Process", e.getCause());
} catch (IOException e) {
logger.warn("Something went wrong during Drag and Drop Process", e.getCause());
}
}
#Override
public AcceptCriterion getAcceptCriterion() {
return AcceptAll.get();
}
}
private class DoneTableHandler implements DropHandler{
private static final long serialVersionUID = 1L;
private final Logger logger = LoggerFactory.getLogger(DoneTableHandler.class);
#Override
public void drop(DragAndDropEvent event) {
logger.info("Received Drag and Drop Event from In Done Table.");
DataBoundTransferable t = (DataBoundTransferable) event.getTransferable();
AbstractSelectTargetDetails dropData = ((AbstractSelectTargetDetails) event.getTargetDetails());
Object itemId = t.getItemId();
Long id = (Long) t.getSourceContainer().getItem(itemId).getItemProperty("ID").getValue();
try {
Task taskToAdd = taskController.getById(id.intValue());
String author = taskController.getAuthorInTask(taskToAdd.getId().intValue()).getUserName();
if (t.getSourceComponent() != doneTable && dropData.getTarget().equals(inProgressTable) ){
doneTable.addItem(new Object[] { taskToAdd.getId(), taskToAdd.getHeadLine(),
taskToAdd.getTaskType(), author, taskToAdd.getStatus() }, giveEncreasedAvailableTableId(TableType.DONE));
inProgressTable.removeItem(itemId);
doneTasks.add(taskToAdd);
inProgressTasks.remove(taskToAdd);
}else if(t.getSourceComponent() != doneTable && dropData.getTarget().equals(openTable)){
doneTable.addItem(new Object[] { taskToAdd.getId(), taskToAdd.getHeadLine(),
taskToAdd.getTaskType(), author, taskToAdd.getStatus() }, giveEncreasedAvailableTableId(TableType.DONE));
openTable.removeItem(itemId);
doneTasks.add(taskToAdd);
openTasks.remove(taskToAdd);
}else{
return;
}
logger.info("Sending updates of taskboard to webservice...");
taskToAdd.setStatus(WorkflowStatusConfigurator.done);
HttpResponse response = taskController.put(taskToAdd, taskToAdd.getId().intValue());
MainView.navigator.navigateTo(TaskboardView.VIEW_NAME);
}catch (ClientProtocolException e) {
logger.warn("Something went wrong during Drag and Drop Process", e.getCause());
} catch (IOException e) {
logger.warn("Something went wrong during Drag and Drop Process", e.getCause());
}
}
#Override
public AcceptCriterion getAcceptCriterion() {
return AcceptAll.get();
}
}
}
Has anyone any idea or at least a clue why this doesn't work? I wrote a code following the same pattern or way and it worked fine. The only difference is that there I don't use Horizontal Layout. And now the in Progress and Done Table don't react to draggin a row on them.
Off-topic: why do you have #Theme("valo") on your view? As far as I know that's used with the UI class...
On-topic:
As I was saying in my comment I don't think it's related to HorizontalLayout. Either you may have misunderstood the drag source and drop target concepts or it simply slipped in the code.
As it's also described in the docs the dragging starts from a source, and the event of dropping the data on the target is handled by a DropHandler.
If you take a look at your sources, DoneTableHandler for example, you can see
if (t.getSourceComponent() != doneTable && dropData.getTarget().equals(inProgressTable) ){
...
}else if(t.getSourceComponent() != doneTable && dropData.getTarget().equals(openTable)){
...
}else{
return;
}
Since you're listening for drops on your doneTable it will be the target and sources can only be the openTable or inProgressTable, not the other way around. I have a hunch that if you're going to add a log line in the else branch you'll see it on each drag & drop.
Below you can see a working sample in Vaadin 7.7.3 with a HorizontalLayout and 3 tables, similar to yours. It's quick and dirty so there's room for improvement (suggestions are welcome) but (eg: position of dropped items), it supports multirow drag and also the AcceptCriterion filters drops from the source table or any other component than the expected ones:
public class DragAndDropTables extends HorizontalLayout {
public DragAndDropTables() {
// leave some space between the tables
setSpacing(true);
// tables
Table toDoTable = createTable("To do");
Table inProgressTable = createTable("In progress");
Table doneTable = createTable("Done");
// drop handlers which allow only drops from expected sources
configureDragAndDrop(toDoTable, inProgressTable, doneTable);
configureDragAndDrop(inProgressTable, toDoTable, doneTable);
configureDragAndDrop(doneTable, toDoTable, inProgressTable);
// some table to make sure AcceptCriterion allows drops only from expected sources
Table tableNotAcceptableForDrops = createTable("Drops from here will not be accepted");
configureDragAndDrop(tableNotAcceptableForDrops);
tableNotAcceptableForDrops.addItem(new Task(100, "Not droppable task"));
// add some dummy data
for (int i = 0; i < 10; i++) {
toDoTable.addItem(new Task(i, "Task " + i));
}
// add the tables to the UI
addComponent(toDoTable);
addComponent(inProgressTable);
addComponent(doneTable);
addComponent(tableNotAcceptableForDrops);
}
private Table createTable(String caption) {
// basic table setup
Table table = new Table(caption);
BeanItemContainer<Task> itemContainer = new BeanItemContainer<>(Task.class);
table.setContainerDataSource(itemContainer);
table.setMultiSelect(true);
table.setSelectable(true);
table.setPageLength(10);
return table;
}
private void configureDragAndDrop(Table table, Table... acceptedSources) {
// drag & drop configuration
table.setDragMode(Table.TableDragMode.MULTIROW);
table.setDropHandler(new DropHandler() {
#Override
public void drop(DragAndDropEvent event) {
// where the items are dragged from
Table source = (Table) event.getTransferable().getSourceComponent();
// where the items are dragged to
Table target = (Table) event.getTargetDetails().getTarget();
// unique collection of dragged tasks
HashSet<Task> draggedTasks = new HashSet<>();
// https://vaadin.com/api/com/vaadin/ui/Table.TableDragMode.html
// even in MULTIROW drag mode, the event contains only the row on which the drag started
draggedTasks.add((Task) event.getTransferable().getData("itemId"));
// we'll get the rest, if any, from the source table selection value
draggedTasks.addAll((Collection<Task>) source.getValue());
// remove items from source table
draggedTasks.forEach(((Table) source)::removeItem);
// add items to destination table
target.addItems(draggedTasks);
}
#Override
public AcceptCriterion getAcceptCriterion() {
// accept drops only from specified tables, and prevent drops from the source table
return new SourceIs(acceptedSources);
}
});
}
// basic bean for easy binding
public static class Task {
private String name;
private int id;
public Task(int id, String name) {
this.name = name;
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
}
Result:
I have a simple media player and in one of the classes I need to retrieve the metadata of the media. Thus far, I have successfully extracted the metadata, however when I attempt to use the values, the Strings returned are blank.
String album = "", artist = "", title = "", year = "";
...
public void addListItems(final Pane layout, final Stage stage, final Scene scene) {
String[] sList = s.split("\\\\");
try {
Media media = new Media(new File(s).toURI().toURL().toString());
media.getMetadata().addListener(new MapChangeListener<String, Object>() {
public void onChanged(Change<? extends String, ? extends Object> arg0) {
handleMetadata(arg0.getKey(), arg0.getValueAdded());
}
});
} catch (MalformedURLException e) {
e.printStackTrace();
}
System.out.println(album); //Here, album returns as ""
final Button lab = new Button(album + "--" + sList[sList.length - 1]);
}
...
public void handleMetadata(String key, Object value) {
if (key.equals("album")) {
album = value.toString(); //Here album returns as value.toString() correctly
} else if (key.equals("artist")) {
artist = value.toString();
} else if (key.equals("title")) {
title = value.toString();
} else if (key.equals("year")) {
year = value.toString();
}
}
I have done research on this topic, but the results I viewed did not help my circumstance. I greatly appreciate any assistance.
I want to sort rows in CellTable when adding new.
To markup UI I use UIBinder:
<g:HTMLPanel>
<c:CellTable pageSize='100' ui:field='myTable'/>
<c:SimplePager ui:field='myPager' location='CENTER'/>
</g:HTMLPanel>
In the widget I created a table and pagination:
#UiField(provided=true) CellTable<myDTO> myTable;
SimplePager.Resources pagerResources = GWT.create(SimplePager.Resources.class);
myPager = new SimplePager(TextLocation.CENTER, pagerResources, false, 0, true);
myTable = new CellTable<myDTO>();
Then I installed a selection model:
final NoSelectionModel<myDTO> selectionModel = new NoSelectionModel<myDTO>();
selectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
public void onSelectionChange(SelectionChangeEvent event) {
clickedObject = selectionModel.getLastSelectedObject();
}
});
myTable.setPageSize(50);
myTable.setSelectionModel(selectionModel);
And added a few columns:
Column<myDTO, String> column1 = new Column<myDTO, String>(new TextCell()) {
#Override
public String getValue(myDTO data) {
return data.getSomeData1();
}
};
Column<myDTO, String> column2 = new Column<myDTO, String>(new TextCell()) {
#Override
public String getValue(myDTO data) {
return data.getSomeData2();
}
};
...
Column<myDTO, String> columnN = new Column<myDTO, String>(new TextCell()) {
#Override
public String getValue(myDTO data) {
return data.getSomeDataN();
}
};
myTable.addColumn(column1, "name of column1");
myTable.addColumn(column2, "name of column2");
...
myTable.addColumn(columnN, "name of columnN");
Next, I create AsyncDataProvider:
AsyncDataProvider<myDTO> provider = new AsyncDataProvider<myDTO>() {
#Override
// is called when the table requests a new range of data
protected void onRangeChanged(HasData<myDTO> display) {
final int start = display.getVisibleRange().getStart();
final int lenght = display.getVisibleRange().getLength();
myService.findAll(new AsyncCallback<List<myDTO>>() {
public void onFailure(Throwable caught) {
// exception handling here
}
public void onSuccess(List<myDTO> data) {
updateRowCount(data.size(), true);
updateRowData(0, data);
}
});
}
};
provider.addDataDisplay(myTable);
If I use this approach, then new rows are added to the end of the table.
I need to automatically sort rows when added.
How can I do it?
Create a sort handler right after creating your provider:
ListHandler<myDTO> sortHandler = new ListHandler<myDTO>(provider.getList());
myTable.addColumnSortHandler(sortHandler);
Then for each column that you want to sort by, set a comparator and add the column to the sort list, e.g.:
sortHandler.setComparator(column1, new Comparator<myDTO>() {
public int compare(myDTO dto1, myDTO dto2) {
// This is an example, how you compare them depends on the context
return dto1.getSomeData1().compareTo(dto2.getSomeData1());
}
});
myTable.getColumnSortList().push(column1);
You can call the push() method multiple times to sort by multiple columns. You can also call it twice for the same column to invert its sorting order (ascending/descending).
I want to retrieve the time and the real-time last Price as double instead of having an output like
DataChangeEvent{ESA Index,ASK_SIZE: 204==>192}
from the code below
DataChangeListener lst = new DataChangeListener() {
#Override
public void dataChanged(DataChangeEvent e) {
System.out.println(e);
}
};
SubscriptionBuilder builder = new SubscriptionBuilder()
.addSecurity("ESA Index")
.addField(RealtimeField.LAST_PRICE)
.addField(RealtimeField.ASK)
.addField(RealtimeField.ASK_SIZE)
.addListener(lst);
session.subscribe(builder);
Thread.sleep(3000);
Just saw your question so it's probably a little late - but here it is anyway. DataChangeEvent contains the ticker, the field, the new and old price:
DataChangeListener lst = new DataChangeListener() {
#Override public void dataChanged(DataChangeEvent e) {
String ticker = e.getSource();
String field = e.getDataName();
double oldValue = e.getOldValue().asDouble();
double newValue = e.getNewValue().asDouble();
}
};