Redirecting output to table in Java Swing - java

Newbie here, I have a problem, redirecting my output to a Jtable. The data is coming from a different class that does the real work which is Scanner.java.
With this said, Scanner.java could print what i want on console but since I added gui which am still learning I have created a new class MainFrame.java and I want search or scan result form Scanner.java to be populated in my JTable but am finding it hard to get the login.
Scanner.java
public void getCompanyProfile(){
Document sourceCode;
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
List<String> allLinks = results();
Document sourceCode;
int counter = 1;
for (String link : allLinks){
System.out.println("Link #:" + counter + " " + link);
sourceCode = PageVisitor.getHtmlSource(link);
Elements profile = sourceCode.select("div.company a.cd");
for (Element links : profile) {
String linkHref = links.attr("href");
System.out.println(linkHref);
setUserData(linkHref);
}
counter++;
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private void setUserData(String url) throws IOException{
Extractor data = new Extractor();
// Scan each page alibaba initial result
data.setProfile(url);
this.companyName = data.getName();
this.country = data.getCountry();
HashSet<String> webites = data.getSellerUrls();
this.webAndEmail = new HashMap<String, HashSet<String>>();
HashSet<String> emails;
for (String webs: webites){
emails = data.emailExtractor(webs);
webAndEmail.put(webs, emails);
for (String anEmail : emails){
//This is the part i want to be displayed in my JTable Component.
System.out.println("Company=" +companyName + ", country=" + country + ", web="
+ webs + ", email=" + anEmail);
}
}
}
public String getProductName(){
return this.product;
}
public String getSource(){
return this.source;
}
public String getCompanyName(){
return this.companyName;
}
public String getCountry(){
return this.country;
}
public Map<String, HashSet<String>> getWebandEmail(){
return this.webAndEmail;
}
Finally, this is my MainFrame.java file below .
![JButton btnStart = new JButton("Start");
btnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnStart.setBounds(197, 166, 75, 29);
frame.getContentPane().add(btnStart);
//more statements like the above to establish all col. titles
String\[\] columnNames = {"Company Name", "Email", "Website", "Country", "Product", "Source"};
//Sample data to be printed
Object\[\]\[\] data =
{
{"Code Java Ltd", "bingo#codejava.net", "http://www.codejava.com", "Universe", "Polythecnic", "Ebay - B2B"},
};
DefaultTableModel model = new DefaultTableModel(data, columnNames) {
#Override
public boolean isCellEditable(int row, int column) {
//all cells false
return false;
}
};
resultTable = new JTable(model);
//resultTable.setBounds(37, 259, 553, 143);
resultTable.getColumnModel().getColumn(0).setPreferredWidth(150);
resultTable.getColumnModel().getColumn(1).setPreferredWidth(150);
resultTable.getColumnModel().getColumn(2).setPreferredWidth(150);
resultTable.getColumnModel().getColumn(3).setPreferredWidth(150);
resultTable.getColumnModel().getColumn(4).setPreferredWidth(100);
resultTable.getColumnModel().getColumn(5).setPreferredWidth(100);
resultTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
JScrollPane scrollPane = new JScrollPane( resultTable );
scrollPane.setBounds(37, 259, 806, 143);
frame.getContentPane().add( scrollPane );
//frame.add(resultTable);
JButton button = new JButton("Stop");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
button.setBounds(289, 166, 75, 29);
frame.getContentPane().add(button);][1]
This is what am trying to attain.
My other idea is to write the content to CSV from Scanner.java class file and read the file lated to populate the table. But like I said, am a beginner still don't think it would be that easy. So I kindly need someone to point me in the right direction.

Basically, you want to load your data from outside the Event Dispatching Thread, so as not to block the UI and make it "hang".
Next, you need some way for the Scanner to publish information it has generated, there are a number of ways you might do this, but the simplest might to use something like a Produce/Consumer Pattern.
With the Scanner acting as the producer, we need some way to inform the consumer that new content is available. Start with a simple interface...
public interface Consumer {
public void publish(String company, String country, String webLink, String email);
}
Note, I normally prefer to use objects (like a POJO), but I'm trying to keep it simple.
Next, we need to modify the Scannner to work with out Consumer...
public class Scanner {
public void getCompanyProfile(Consumer consumer) {
Document sourceCode;
List<String> allLinks = results();
Document sourceCode;
int counter = 1;
for (String link : allLinks) {
System.out.println("Link #:" + counter + " " + link);
sourceCode = PageVisitor.getHtmlSource(link);
Elements profile = sourceCode.select("div.company a.cd");
for (Element links : profile) {
String linkHref = links.attr("href");
System.out.println(linkHref);
setUserData(linkHref);
}
counter++;
}
}
private void setUserData(String url, Consumer consumer) throws IOException {
Extractor data = new Extractor();
// Scan each page alibaba initial result
data.setProfile(url);
this.companyName = data.getName();
this.country = data.getCountry();
HashSet<String> webites = data.getSellerUrls();
this.webAndEmail = new HashMap<String, HashSet<String>>();
HashSet<String> emails;
for (String webs : webites) {
emails = data.emailExtractor(webs);
webAndEmail.put(webs, emails);
for (String anEmail : emails) {
consumer.publish(companyName, country, webs, anEmail);
}
}
}
public String getProductName() {
return this.product;
}
public String getSource() {
return this.source;
}
public String getCompanyName() {
return this.companyName;
}
public String getCountry() {
return this.country;
}
public Map<String, HashSet<String>> getWebandEmail() {
return this.webAndEmail;
}
}
Now, we need some way to get the Scanner started and producing data, first we create the basic UI and then we start a SwingWorker, passing a reference of the TableModel to it, so it can add the new rows.
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
DefaultTableModel model = new DefaultTableModel(new String[]{"Company Name", "Email", "Website", "Country", "Product", "Source"}, 0);
JTable table = new JTable(model);
// Initialise remainder of the UI...
ScannerWorker worker = new ScannerWorker(model);
worker.execute();
}
});
And the SwingWorker to hold it all together...
public class ScannerWorker extends SwingWorker<Object, String[]> implements Consumer {
private DefaultTableModel tableModel;
public ScannerWorker(DefaultTableModel tableModel) {
this.tableModel = tableModel;
}
#Override
protected Object doInBackground() throws Exception {
Scanner scanner = new Scanner();
scanner.getCompanyProfile(this);
return null;
}
#Override
public void publish(String company, String country, String webLink, String email) {
publish(new String[]{company, email, webLink, country, "", ""});
}
#Override
protected void process(List<String[]> chunks) {
for (String[] rowData : chunks) {
tableModel.addRow(rowData);
}
}
}
Take a closer look at Worker Threads and SwingWorker and How to Use Tables for more details

Related

Getting database values CODENAME ONE

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)

Drag and Drop between tables in horizontalLayout doesn't work

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:

Change Value of String Based on Media Metadata

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.

Adding rows with sorting in CellTable

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).

retrieve real-time data from JBloomberg API

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();
}
};

Categories