On clicking the JTable row, the valueChanged(ListSelectionEvent e) method is calling multiple times - jframe

I have the JTable with multiple columns. When I clicked on the table rows, the value changed method call multiple times and at last it throw an error of
java.lang.ArrayIndexOutOfBoundsException: -1
My code is
subjectTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
System.out.println("Value IS Adjusting --> " + e.getValueIsAdjusting());
try {
if(subjectTable.getSelectedRow() == -1)
return;
if(!e.getValueIsAdjusting()) {
System.out.println("Selected Row --> " + subjectTable.getSelectedRow());
System.out.println("Selected Value of Column 0 --> " + subjectTable.getValueAt(subjectTable.getSelectedRow(), 0).toString());
cmbClass.setSelectedItem(subjectTable.getValueAt(subjectTable.getSelectedRow(), 0).toString());
txtSubjectName.setText(subjectTable.getValueAt(subjectTable.getSelectedRow(), 1).toString());
txtFullMarks.setText(subjectTable.getValueAt(subjectTable.getSelectedRow(), 2).toString());
txtPassMarks.setText(subjectTable.getValueAt(subjectTable.getSelectedRow(), 3).toString());
cmbGrade.setSelectedItem(subjectTable.getValueAt(subjectTable.getSelectedRow(), 4).toString());
}
} catch (IndexOutOfBoundsException ex) {
ex.printStackTrace();
new KILogger("Error in the value changed, Edit Subject table", ex);
}
}
});
I got the error like this:

I didn't know what is this issue. But now it is solved by doing following code:
subjectTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
try {
if(subjectTable.getSelectedRow() == -1)
return;
if(!e.getValueIsAdjusting()) {
txtSubjectName.setText(subjectTable.getValueAt(subjectTable.getSelectedRow(), 1).toString());
txtFullMarks.setText(subjectTable.getValueAt(subjectTable.getSelectedRow(), 2).toString());
txtPassMarks.setText(subjectTable.getValueAt(subjectTable.getSelectedRow(), 3).toString());
cmbGrade.setSelectedItem(subjectTable.getValueAt(subjectTable.getSelectedRow(), 4).toString());
}
} catch (IndexOutOfBoundsException ex) {
ex.printStackTrace();
new KILogger("Error in the value changed, Edit Subject table", ex);
}
}
}); `

Related

Launching Dialog Box with Data from TableView Row

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

Camera Zoom in/out null pointer exception

My code works fine when i add the zoom code it gives null pointer exception.
I have written the below code inside the preview class. I am new in android please help thanks in advance.
my code is
int currentZoomLevel = 0, maxZoomLevel = 0;
public void surfaceChanged(SurfaceHolder surfaceHolder, int format,
int width, int height) {
// start preview with new settings
try {
parameters = mCamera.getParameters();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Display display = ((WindowManager) context
.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
if (display.getRotation() == Surface.ROTATION_0) {
try {
parameters.setPreviewSize(height, width);
mCamera.setDisplayOrientation(90);
} catch (Exception e) {
e.printStackTrace();
}
}
if (display.getRotation() == Surface.ROTATION_90) {
try {
parameters.setPreviewSize(width, height);
} catch (Exception e) {
e.printStackTrace();
}
}
if (display.getRotation() == Surface.ROTATION_180) {
try {
parameters.setPreviewSize(height, width);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (display.getRotation() == Surface.ROTATION_270) {
try {
parameters.setPreviewSize(width, height);
mCamera.setDisplayOrientation(180);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
This is whera i start zooming. i have add zoom control in side my layout
ZoomControls zoomControls = (ZoomControls) findViewById(R.id.zoom);
if (parameters.isZoomSupported()) {
final int maxZoomLevel = parameters.getMaxZoom();
Log.i("max ZOOM ", "is " + maxZoomLevel);
zoomControls.setIsZoomInEnabled(true);
zoomControls.setIsZoomOutEnabled(true);
zoomControls.setOnZoomInClickListener(new OnClickListener() {
public void onClick(View v) {
if (currentZoomLevel < maxZoomLevel) {
currentZoomLevel++;
mCamera.startSmoothZoom(currentZoomLevel);
parameters.setZoom(currentZoomLevel);
mCamera.setParameters(parameters);
}
}
});
zoomControls.setOnZoomOutClickListener(new OnClickListener() {
public void onClick(View v) {
if (currentZoomLevel > 0) {
currentZoomLevel--;
parameters.setZoom(currentZoomLevel);
mCamera.setParameters(parameters);
}
}
});
} else
zoomControls.setVisibility(View.GONE);
try {
mCamera.setPreviewDisplay(surfaceHolder);
mCamera.startPreview();
} catch (Exception e) {
// intentionally left blank for a test
}
}

sessionObject.getAgenda().getAgendaGroup().setFocus() UnsupportedOperationException

My drool is working fine when I don't have agenda group but if I set focus i'm getting the following error:
package drools;
import droolsexec.Message;
import droolsexec.Customer;
rule "Good Bye"
agenda-group "group1"
dialect "java"
when
message: Message( status =="GOODBYE" )
customer: Customer(name == "NEHA")
then
System.out.println( message.getStatus());
end
This is my rule and i'm executing it by:
public class ExecuteDrools {
private static PackageBuilder pbuilder = new PackageBuilder();
private static StatefulSession sessionObject;
private static RuleBase rbase = RuleBaseFactory.newRuleBase();
public void runDrools(ArrayList list){
initialiseDrools();
initiliseMessageObject(list);
runRules();
}
private void initialiseDrools() {
//1. Read the DRL File and add to package builder
try {
Reader reader = new InputStreamReader(ExecuteDrools.class.getResourceAsStream("/HelloWorld.drl"));
pbuilder.addPackageFromDrl(reader);
} catch (DroolsParserException ex) {
Logger.getLogger(ExecuteDrools.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(ExecuteDrools.class.getName()).log(Level.SEVERE, null, ex);
}
//2. Check for any errors
PackageBuilderErrors errors = pbuilder.getErrors();
if (errors.getErrors().length > 0) {
System.out.println("Some errors exists in packageBuilder");
for (int i = 0; i < errors.getErrors().length; i++) {
System.out.println(errors.getErrors()[i]);
}
throw new IllegalArgumentException("Could not parse knowledge.");
}
//3. Add package to rule base
try {
rbase.addPackage(pbuilder.getPackage());
} catch (Exception e) {
System.out.println("Error: "+ e);
}
}
private void initiliseMessageObject(ArrayList list) {
sessionObject = rbase.newStatefulSession();
Iterator itr = list.iterator();
while(itr.hasNext()){
sessionObject.insert(itr.next());
}
}
private void runRules() {
sessionObject.getAgenda().getAgendaGroup("group2").setFocus();
sessionObject.fireAllRules();
}
}
I'm getting the following error:
Exception in thread "main" java.lang.UnsupportedOperationException
at org.drools.common.BinaryHeapQueueAgendaGroup.setFocus(BinaryHeapQueueAgendaGroup.java:156)
at droolsexec.ExecuteDrools.runRules(ExecuteDrools.java:83)
at droolsexec.ExecuteDrools.runDrools(ExecuteDrools.java:36)
at droolsexec.MainClass.executeRules(MainClass.java:23)
at droolsexec.MainClass.main(MainClass.java:9)
you do not have an agenda group group2 in your drl file... you have it named group 1

Markes dump displays nulls for IMarker.LINE_NUMBER and IMarker.CHAR_START Plugin development markers

I have following generic code that dumps all the markers with all the attibutes in the system. If I set some breakpoints the value for both LINE_NUMBER and IMarker.CHAR_START is always displaed as null despite them having a clear value.
Can Anybody help understand that?
private void printAllMarkers() {
IMarker[] markers = null;
IWorkspace root = ResourcesPlugin.getWorkspace();
IProject projects[] = root.getRoot().getProjects();
for (IProject p : projects) {
try {
markers = p.findMarkers(IMarker.MARKER, true, IResource.DEPTH_INFINITE);
System.out.println("\nAll Markers Are: ");
for (IMarker m : markers) {
System.out.println("-----------Marker of Type: " + m.getType());
dumpMarker(m);
}
} catch (CoreException e) {
e.printStackTrace();
}
}
}
public static void dumpMarker(IMarker m) {
try {
for (String attrName : m.getAttributes().keySet()) {
System.out.println("Attribute:" + attrName + "=" + m.getAttribute(attrName, null));
}
} catch (CoreException e) {
e.printStackTrace();
}
}
I found the problem. It's an Eclipse bug that displays the value as null if it comes from a 'supertype"
so getAttribute(attrName, null) will return null for lineStart even if the attribute exists.

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;