Launching Dialog Box with Data from TableView Row - javafx-8

I'm attempting to launch an Edit Customer Window with text fields filled with reference from the rows of a table. The Table and Dialog both have different controller classes.
Here's the code snippet from the table in question that gives us the required customerID when a user double clicks on a row.
Table Controller: CustomersController:
#Override
public void initialize(URL location, ResourceBundle resources) {
populateCustomerTable();
tableListeners(null);
}
void tableListeners(CustomerData customerData){
tblcustomer.setRowFactory(tr -> {
TableRow<CustomerData> row = new TableRow<>();
row.setOnMouseClicked(event -> {
if (event.getClickCount() == 2 && (!row.isEmpty())) {
int selectedCustomerID = row.getItem().getCustomerID();
System.out.println("A certain row: " + selectedCustomerID + " has been clicked!");
Stage stage = new Stage();
FXMLLoader loader = new FXMLLoader();
try {
Parent root = loader.load(getClass().getResource("../view/popups/edit_customer.fxml"));
stage.setScene(new Scene(root));
stage.setTitle("Editing Existing Customer's Details");
stage.initModality(Modality.APPLICATION_MODAL);
stage.initOwner(btnEditCustomer.getScene().getWindow());
stage.showAndWait();
} catch (IOException e) {
e.printStackTrace();
}
}
});
return row;
});
}
I want selectedCustomerID from the above piece of code to be parsed into the EditCustomerController class hence when the dialog launches, it's text fields should be prepoulated with values suppled from the select query that queries the database with the where condition being tht selectedCustomerID from the CustomersController class.
Code snippet from EditCustomerController class:
#Override
public void initialize(URL location, ResourceBundle resources) {
//populateEditCustomerFields(1);
}
void populateEditCustomerFields(int customerID){
this.customer_ID=customerID;
System.out.println(customer_ID);
try {
con = DatabaseConnection.getConnected();
stmt = con.createStatement();
rs = con.createStatement().executeQuery("SELECT * FROM `h_customers` WHERE `customerID`=" + customer_ID);
while (rs.next()) {
title.setText(rs.getString("title"));
firstName.setText(rs.getString("firstName"));
lastName.setText(rs.getString("lastName"));
nationalID.setText(String.valueOf(rs.getInt("nationalID")));
//dob.setText(rs.getString("DOB"));
mobilePhone.setText(rs.getString("mobilePhone"));
workPhone.setText(rs.getString("workPhone"));
email.setText(rs.getString("email"));
}
} catch (SQLException ex) {
Logger.getLogger(NewRoomController.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
The Idea here is to parse selectedCustomerID from CustomersController into the initialize method of EditCustomerController so the Dialog can launch with the customer details that require editing. I've searched for solutions all over the web and here on StackOverflow, some come close to answering me, some are too complex for my newbie mind, but none has helped. Any solution would be highly appreciated. I will provide any further clarification required.

You can get the controller class and invoke its necessary methods. See this answer for getting controller, then do
editCustomerController.populateEditCustomerFields(selectedCustomerID);
on table row double click.
Further to improve performance, you can load the edit_customer.fxml only once and when the user double clicks, refresh its rendered data with editCustomerController.populateEditCustomerFields(selectedCustomerID).

Related

How to remove MenuBar/ select in lwuit form

I'm trying to remove this select area which shows up as soon as I add a button to my form.
Have attached a screenshot of the same which might help you understand my plight here. I don't want this select area to appear at the bottom of screen.
Please, any suggestion or any pointer would be of great help.
regards.
Below is the code which I'm using.(Xlet project)
public void showMainForm() {
try {
mf = new MainForm();
mf.createMainForm();
mf.show();
} catch (Exception e) {
}
}
public class MainForm extends Form {
MainForm() {
super();
}
private static Container c;
public void createMainForm() {
try {
c = new Container(new CoordinateLayout(800,480));
Button btn = new Button();
btn.setX(0); btn.setY(0);
c.addComponent(btn);
this.getContentPane().addComponent(c);
} catch (Exception e) {
}
}
}
Form code which I tried again...
Form frm = new Form();
frm.getStyle().setBgTransparency(0);
//frm.addComponent(new Button("Button"));
frm.show();
I think that this issue can be solved adding the Command to the Form,not to the Container as you are doing in the attached code.
ADD
I think that I didn't understand what you want to say. Try this code, with my suggestions included
public void showMainForm() {
try {
mf = new MainForm();
mf.createMainForm();
mf.show();
} catch (Exception e) {
}
}
public class MainForm extends Form {
MainForm() {
super();
}
private static Container c;
public void createMainForm() {
try {
c = new Container(new CoordinateLayout(800,480));
// Button btn = new Button();
// btn.setX(0); btn.setY(0);
// c.addComponent(btn);
// this.getContentPane().addComponent(c);
Command c = new Command("command");
addCommand(c);
} catch (Exception e) {
}
}
}

Can't compile Lucene project with Eclipse

Here's my code:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import org.apache.lucene.index.CorruptIndexException;
public class Main
{
public static void main()
{
//Index index = new Index();
String[] titleAndContent = parseFile("files/methode.txt");
Index index = new Index("files",null);
try
{
index.openIndex(true);
index.addDocument(titleAndContent[0], titleAndContent[1], "files/methode.txt");
}
catch (CorruptIndexException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String[] parseFile(String path)
{
String[] titleAndContent = new String[2];
File file = new File(path);
try
{
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line = new String();
String content = new String();
try
{
while((line = br.readLine()) != null)
{
if (line.substring(0,min(6,line.length())).equals("title:"))
{
titleAndContent[0] = line.substring(6,line.length());
}
else
{
if (line.substring(0,min(8,line.length())).equals("content:"))
{
content += line.substring(8,line.length())+"\n";
}
else
{
content += line+"\n";
}
}
}
}
catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
titleAndContent[1] = content;
try
{
fr.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return titleAndContent;
}
public static int max (int a, int b)
{
if (a<b)
{
return b;
}
return a;
}
public static int min (int a, int b)
{
if (a<b)
{
return a;
}
return b;
}
}
The problem is, I can't compile my Lucene projet under Eclipse. It keeps telling me:
ERROR: index path not specified
Usage: java org.apache.lucene.index.CheckIndex pathToIndex [-fix] [-segment X] [-segment Y]
-fix: actually write a new segments_N file, removing any problematic segments
-segment X: only check the specified segments. This can be specified multiple
times, to check more than one segment, eg '-segment _2 -segment _a'.
You can't use this with the -fix option
**WARNING**: -fix should only be used on an emergency basis as it will cause
documents (perhaps many) to be permanently removed from the index. Always make
a backup copy of your index before running this! Do not run this tool on an index
that is actively being written to. You have been warned!
Run without -fix, this tool will open the index, report version information
and report any exceptions it hits and what action it would take if -fix were
specified. With -fix, this tool will remove any segments that have issues and
write a new segments_N file. This means all documents contained in the affected
segments will be removed.
This tool exits with exit code 1 if the index cannot be opened or has any
corruption, else 0.
I tried everything to make it work, and as the whole web says, I used
-ea:org.apache.lucene... pathToIndex -fix
as argument of compilation. But whatever I put instead of pathToIndex, it keeps telling me
Unexpected argument pathToIndex (or whatever instead)
How can I get this f... project work?
Thank you in advance.
Edit: Of course I've imported all Lucene JARs.
Actually, I started the project over by creating a simple Main class and a main method inside it and tried to compile it immediately. And it worked fine, this time. Note you should show the Main class on your screen tab before compiling in Eclipse.

how to update jfree line chart in RCP View

I have four views in Eclipse RCP App. In that 3 View are responsible to show the multiline graphs. i am using a switch case for drawing the graph continuously until other views are get focused. But the view are not showing the updated chart.
The following is the case for update the graph. i have two datasets for sample updation of the view.
All the replies are appreciated.
case 1:
System.out.println("in Case "+selectedViewId);
while(selectedViewId==1){
try {
Display.getDefault().syncExec(new Runnable() {
public void run() {
while(count<20) {
count++;
System.err.println("Countttttttt "+count);
if(count%2==0){
System.err.println(".....Oneeeeeeee");
IViewPart vp = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().findView("RCP.CPU");
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().hideView(vp);
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().resetPerspective();
try {
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView("RCP.CPU");
} catch (PartInitException e1) {
e1.printStackTrace();
}
int value = CPU.value=1;
CPU cpuView = CPUSingleton.getCPUObject();
}
else {
System.err.println(".....tWOOOOOOOOOOOOOO");
IViewPart vp = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().findView("RCP.CPU");
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().hideView(vp);
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().resetPerspective();
try {
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView("RCP.CPU");
} catch (PartInitException e) {
e.printStackTrace();
}
int value = CPU.value=2;
CPU cpuView = CPUSingleton.getCPUObject();
}
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
break;

How do I upload file in Vaadin ui Portlet?

I am creating a Portlet project using Vaadin and Liferay6.0.
I need to upload a csv file from ui and read the file.
My class is as fllows:
#SuppressWarnings("serial")
public void init() {
Window window = new Window("Vaadin Portlet Application");
setMainWindow(window);
window.addComponent(new Label("Hello Vaadin user!"));
window.addComponent(new Label("We are here"));
final TextField tf = new TextField("Device Name:");
// Create the Upload component.
final Upload upload =
new Upload("Upload the file here", null);
// Use a custom button caption instead of plain "Upload".
upload.setButtonCaption("Upload Now");
try{
System.out.println("I am here only");
final DeviceManager dManager = new DeviceManager();
final DeviceSoap[] devices = dManager.getAll();
//getDeviceByName("207.20.47.137");
for (DeviceSoap deviceSoap : devices) {
window.addComponent(new Label("Device Name! "+deviceSoap.getName()));
}
window.addComponent(tf);
Button submitBttn = new Button("Add Device");
Button updateBttn = new Button("Update Device");
window.addComponent(submitBttn);
// Handle button clicks
submitBttn.addListener(new Button.ClickListener() {
#Override
public void buttonClick(ClickEvent event) {
// If the field value is bad, set its error.
// (Allow only alphanumeric characters.)
DeviceSoap d = new DeviceSoap();
d.setName(tf.getValue().toString());
try {
dManager.createDevice(d);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
updateBttn.addListener(new Button.ClickListener() {
#Override
public void buttonClick(ClickEvent event) {
// If the field value is bad, set its error.
// (Allow only alphanumeric characters.)
DeviceSoap d = devices[1];
d.setName(tf.getValue().toString());
try {
dManager.createDevice(d);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
upload.addListener((Upload.SucceededListener) this);
upload.addListener((Upload.FailedListener) this);
window.addComponent(upload);
}catch(Exception e){
e.printStackTrace();
}
}
Thanks
Hiamsnhu
I'm doing the same thing, and in reading your code, I see that you forgot making:
window.addComponent(updateBttn);
Hope this works.

GWT client "throws Exception" cause compling problem

I try to use get result from a api called j-calais, and then out put the result on a web page, i write all the code in client, but it cant compile right, dont know why??? please help. the source code like below:
there is no obvious error arise, but it cant be compile successfully..... thanks a lot:
public void onModuleLoad() {
// Create table for stock data.
stocksFlexTable.setText(0, 0, "Type");
stocksFlexTable.setText(0, 1, "Name");
// Assemble Add Stock panel.
addPanel.add(newSymbolTextBox);
addPanel.add(addStockButton);
// Assemble Main panel.
mainPanel.add(stocksFlexTable);
mainPanel.add(addPanel);
mainPanel.add(lastUpdatedLabel);
// Associate the Main panel with the HTML host page.
RootPanel.get("stockList").add(mainPanel);
// Move cursor focus to the input box.
newSymbolTextBox.setFocus(true);
// Listen for mouse events on the Add button.
addStockButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
try {
addStock();
} catch (Exception e) {
e.printStackTrace();
}
}
});
// Listen for keyboard events in the input box.
newSymbolTextBox.addKeyPressHandler(new KeyPressHandler() {
public void onKeyPress(KeyPressEvent event) {
if (event.getCharCode() == KeyCodes.KEY_ENTER) {
try {
addStock();
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
}
private void addStock() throws Exception {
final String url_s = newSymbolTextBox.getText().toUpperCase().trim();
newSymbolTextBox.setFocus(true);
newSymbolTextBox.setText("");
int row = stocksFlexTable.getRowCount();
CalaisClient client = new CalaisRestClient("ysw5rx69jkvdnzqf6sgjduqj");
System.out.print("read success...\n");
URL url = new URL(url_s);
CalaisResponse response = client.analyze(url);
for (CalaisObject entity : response.getEntities()) {
System.out.println(entity.getField("_type") + ":"
+ entity.getField("name"));
stocks.add(entity.getField("_type"));
stocksFlexTable.setText(row, 0, entity.getField("_type"));
stocksFlexTable.setText(row, 1, entity.getField("name"));
}
for (CalaisObject topic : response.getTopics()) {
System.out.println(topic.getField("categoryName"));
}
}
}
GWT only handles unchecked exceptions so you can throw Runtime Exceptions
or write your own Exception that extends from Runtime Exception then it will not cause any compile time problem
void f() throws NullPointerException // will not cause any problem because it is Runtime exception so unchecked
void f() throws IllegalAccessException // it is checked exception so there will be problem at compile time