javafx IllegalArguementException when popup is open and mouse is clicked on the background stage - javafx-2

on click of it i am launching a popup. Pop has a dynamically created stackpane with a tableview. If i double click a row in table or i enter esc its working fine.
Issue is when i click anywhere on the background stage it gives me following error. How to close the popup when i click on the stage from where the popup is launched. Please suggest.
java.lang.IllegalArgumentException: argument type mismatch
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1435)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:69)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:217)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:170)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:38)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:37)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:92)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:35)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:92)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:53)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:33)
at javafx.event.Event.fireEvent(Event.java:171)
at javafx.scene.Scene$MouseHandler.process(Scene.java:3324)
at javafx.scene.Scene$MouseHandler.process(Scene.java:3164)
at javafx.scene.Scene$MouseHandler.access$1900(Scene.java:3119)
at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1559)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2261)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:228)
at com.sun.glass.ui.View.handleMouseEvent(View.java:528)
at com.sun.glass.ui.View.notifyMouse(View.java:922)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.access$100(WinApplication.java:29)
at com.sun.glass.ui.win.WinApplication$3$1.run(WinApplication.java:73)
at java.lang.Thread.run(Thread.java:722)
Below is my code
public void trkTripNoBtnClick(ActionEvent ae){
StackPane st = new StackPane();
final TableView<GatePassDTO> tripListTableView = new TableView<GatePassDTO>();
TableColumn<GatePassDTO,String> colTrkTripNo = new TableColumn<GatePassDTO,String>();
TableColumn<GatePassDTO,Date> colGatePassDttm = new TableColumn<GatePassDTO,Date>();
TableColumn<GatePassDTO,String> colTruckNo = new TableColumn<GatePassDTO,String>();
TableColumn<GatePassDTO,String> colBat = new TableColumn<GatePassDTO,String>();
colTrkTripNo.setText("Trip No");
colTrkTripNo.setCellValueFactory(new PropertyValueFactory<GatePassDTO,String>("tourPlnNo"));
colGatePassDttm.setText("Gate Pass Dttm");
colGatePassDttm.setCellValueFactory(new PropertyValueFactory<GatePassDTO,Date>("gatePassDttm"));
colTruckNo.setText("Truck");
colTruckNo.setCellValueFactory(new PropertyValueFactory<GatePassDTO,String>("haulPmNo"));
colBat.setText("BAT ID");
colBat.setCellValueFactory(new PropertyValueFactory<GatePassDTO,String>("batId"));
List<GatePassDTO> tripsList = GateIn.getGatePassReference().gateIn_tourPlnNoLookUp(1);
tripListTableView.getColumns().addAll(colTrkTripNo,colGatePassDttm,colTruckNo,colBat);
tripListTableView.setItems(FXCollections.observableList(tripsList));
final Popup popup = new Popup();
popup.setX(txtTrkTripNo.getLayoutX());
popup.setY(txtTrkTripNo.getLayoutY()+txtTrkTripNo.getHeight()+30);
colTrkTripNo.prefWidthProperty().bind(tripListTableView.widthProperty().multiply(0.20));
colGatePassDttm.prefWidthProperty().bind(tripListTableView.widthProperty().multiply(0.45));
colTruckNo.prefWidthProperty().bind(tripListTableView.widthProperty().multiply(0.15));
colBat.prefWidthProperty().bind(tripListTableView.widthProperty().multiply(0.20));
tripListTableView.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>(){
#Override
public void handle(MouseEvent t) {
if(t.getClickCount() == 2 && tripListTableView.getSelectionModel().getSelectedItem() !=null){
GatePassDTO g = tripListTableView.getSelectionModel().getSelectedItem();
popup.hide();
txtTrkTripNo.setText(g.getTourPlnNo());
getTripDetails(txtTrkTripNo.getText());
}
}
});
tripListTableView.addEventHandler(KeyEvent.KEY_PRESSED,new EventHandler<KeyEvent>(){
#Override
public void handle(KeyEvent t) {
if(t.getCode() == KeyCode.ESCAPE)
popup.hide();
}
});
/*Label lblFind = new Label("Find");
TextField txtfind = new TextField();
st.getChildren().add(lblFind);
st.getChildren().add(txtfind);*/
st.getChildren().add(tripListTableView);
VBox v = new VBox(5);
v.getChildren().addAll(st);
popup.getContent().addAll(v);
popup.show(GateIn.primaryStage);
}

you have to check focus property for stage...
try this its worked
stage.focusedProperty().addListener(new ChangeListener<Boolean>
() {
#Override
public void changed(ObservableValue<? extends Boolean> ov, Boolean t, Boolean t1) {
if(t1==false)
{
System.out.println("focus losted");
btn.getScene().getWindow().hide();
}
}
});

Related

Android Logcat strange errors

I am new to Android app developing. While running my app on Genymotion (I have tried with multiple devices), the gradle builds without error, but the emulator says "Unfortunately, Fictiopedia has stopped.", and the Logcat shows lots of errors I can't understand. It's an app that creates its own words by randomly displaying meaningful parts of actual English words and their definition accordingly. (I deleted a large part of the code with words and their definition to make it fit in this question box)
Thanks for helping.
Here, what the Logcat displays and my code:
LOGCAT:
12-27 11:09:05.099 1946-1946/? E/libprocessgroup: failed to make and chown /acct/uid_10059: Read-only file system
12-27 11:09:05.099 1946-1946/? W/Zygote: createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?
12-27 11:09:05.099 1946-1946/? I/art: Late-enabling -Xcheck:jni
12-27 11:09:05.143 1946-1956/? I/art: Debugger is no longer active
12-27 11:09:05.360 1946-1946/? I/InstantRun: starting instant run server: is main process
12-27 11:09:05.454 1946-1946/? W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
12-27 11:09:05.690 1946-1946/? W/ResourceType: Failure getting entry for 0x7f060054 (t=5 e=84) (error -75)
12-27 11:09:05.691 1946-1946/? W/ResourceType: Failure getting entry for 0x7f060054 (t=5 e=84) (error -75)
12-27 11:09:05.692 1946-1946/? D/AndroidRuntime: Shutting down VM
--------- beginning of crash
12-27 11:09:05.693 1946-1946/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.lauramessner.fictiopedia, PID: 1946
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.lauramessner.fictiopedia/com.example.lauramessner.fictiopedia.MainActivity}: android.view.InflateException: Binary XML file line #0: Error inflating class ImageView
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: android.view.InflateException: Binary XML file line #0: Error inflating class ImageView
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:763)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
at com.example.lauramessner.fictiopedia.MainActivity.onCreate(MainActivity.java:26)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
at android.app.ActivityThread.access$800(ActivityThread.java:151) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5254) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 
Caused by: android.content.res.Resources$NotFoundException: Resource ID #0x7f060054
at android.content.res.Resources.getValue(Resources.java:1266)
at android.support.v7.widget.AppCompatDrawableManager.loadDrawableFromDelegates(AppCompatDrawableManager.java:330)
at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:195)
at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:188)
at android.support.v7.content.res.AppCompatResources.getDrawable(AppCompatResources.java:100)
at android.support.v7.widget.AppCompatImageHelper.loadFromAttributes(AppCompatImageHelper.java:58)
at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:78)
at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:68)
at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:106)
at android.support.v7.app.AppCompatDelegateImplV9.createView(AppCompatDelegateImplV9.java:1024)
at android.support.v7.app.AppCompatDelegateImplV9.onCreateView(AppCompatDelegateImplV9.java:1081)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:725)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:806) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:504) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:414) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:365) 
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287) 
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139) 
at com.example.lauramessner.fictiopedia.MainActivity.onCreate(MainActivity.java:26) 
at android.app.Activity.performCreate(Activity.java:5990) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
at android.app.ActivityThread.access$800(ActivityThread.java:151) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5254) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 
12-27 11:09:10.334 1946-1946/? I/Process: Sending signal. PID: 1946 SIG: 9
MY CODE:
package com.example.lauramessner.fictiopedia;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
public void happen(View b){
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView pref = (TextView) findViewById(R.id.pref);
final TextView root = (TextView) findViewById(R.id.root);
final TextView suff = (TextView) findViewById(R.id.suff);
final TextView predef = (TextView) findViewById(R.id.predef);
final TextView rootdef = (TextView) findViewById(R.id.rootdef);
final TextView suffdef = (TextView) findViewById(R.id.suffdef);
final String[] prefixes = {"", "A", "An", "Ab", "Ad", "Ambi", "Ana", "Ante", "Anti", "Apo", "Auto","Bene"};
final String[] roots = {"", "ami", "ann", "anthrop", "aqua"};
final String[] suffixes = {"", "agog", "agogue", "cide", "ectomy"};
ImageButton pushMe = findViewById(R.id.pushMe);
pushMe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final int rando = (int) (Math.random());
suff.setText(prefixes[rando]);
root.setText(roots[rando]);
pref.setText(suffixes[rando]);
if (pref.getText().toString().contains("")) {
predef.setText("");
}
if (pref.getText().toString().contains("A")) {
predef.setText("not ");
}
if (pref.getText().toString().contains("An")) {
predef.setText("without ");
}
if (pref.getText().toString().contains("Ab")) {
predef.setText("away from ");
}
if (pref.getText().toString().contains("Ad")) {
predef.setText("toward ");
}
if (pref.getText().toString().contains("Ambi")) {
predef.setText("both ");
}
if (pref.getText().toString().contains("Ana")) {
predef.setText("again ");
}
if (pref.getText().toString().contains("Ante")) {
predef.setText("before ");
}
if (pref.getText().toString().contains("Anti")) {
predef.setText("against ");
}
if (pref.getText().toString().contains("Apo")) {
predef.setText("away from ");
}
if (pref.getText().toString().contains("Auto")) {
predef.setText("self ");
}
if (pref.getText().toString().contains("Bene")) {
predef.setText("good ");
}
if (root.getText().toString().contains("")) {
rootdef.setText("");
}
if (root.getText().toString().contains("ami")) {
rootdef.setText("love");
}
if (root.getText().toString().contains("ann")) {
rootdef.setText("year");
}
if (root.getText().toString().contains("anthrop")) {
rootdef.setText("human");
}
if (root.getText().toString().contains("aqua")) {
rootdef.setText("water");
}
if (suff.getText().toString().contains("")) {
suffdef.setText("");
}
if (suff.getText().toString().contains("agog")) {
suffdef.setText("Leader ");
}
if (suff.getText().toString().contains("agogue")) {
suffdef.setText("Leader ");
}
if (suff.getText().toString().contains("cide")) {
suffdef.setText("Act of killing ");
}
if (suff.getText().toString().contains("ectomy")) {
suffdef.setText("Surgical removal of ");
}
}
});
}
}

Liferay model listener - on after update handler loop

I have created custom model listener for DLFileEntry in Liferay 6.2 GA6. However, the onAfterUpdate method is called repeatedly even when no change has been made on DLFileEntry.
Let me describe the situation:
The file entry is changed through the content administration in Liferay
The onAfterUpdate method is triggered (this is OK)
The onAfterUpdate method is triggered again and again - even though there is no update made on this entry
I' ve dumped the stack trace when the (unexpected) update event happenes. It looks like the onAfterUpdate is triggered by incrementViewCounter(..)method, which is triggered by BufferedIncrementRunnable class
java.lang.Exception: Stack trace
at java.lang.Thread.dumpStack(Thread.java:1365)
at eu.package.hook.model.listener.DLFileEntryModelListener.onAfterUpdate(DLFileEntryModelListener.java:63)
at eu.package.hook.model.listener.DLFileEntryModelListener.onAfterUpdate(DLFileEntryModelListener.java:32)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.liferay.portal.kernel.bean.ClassLoaderBeanHandler.invoke(ClassLoaderBeanHandler.java:67)
at com.sun.proxy.$Proxy865.onAfterUpdate(Unknown Source)
at com.liferay.portal.service.persistence.impl.BasePersistenceImpl.update(BasePersistenceImpl.java:340)
at com.liferay.portlet.documentlibrary.service.impl.DLFileEntryLocalServiceImpl.incrementViewCounter(DLFileEntryLocalServiceImpl.java:1450)
at sun.reflect.GeneratedMethodAccessor2034.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.liferay.portal.spring.aop.ServiceBeanMethodInvocation.proceed(ServiceBeanMethodInvocation.java:115)
at com.liferay.portal.spring.transaction.DefaultTransactionExecutor.execute(DefaultTransactionExecutor.java:62)
at com.liferay.portal.spring.transaction.TransactionInterceptor.invoke(TransactionInterceptor.java:51)
at com.liferay.portal.spring.aop.ServiceBeanMethodInvocation.proceed(ServiceBeanMethodInvocation.java:111)
at com.liferay.portal.increment.BufferedIncreasableEntry.proceed(BufferedIncreasableEntry.java:48)
at com.liferay.portal.increment.BufferedIncrementRunnable.run(BufferedIncrementRunnable.java:65)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
I have read the documenantation about the bufferend increment in portal.properties docs page. It's not recommended to disable this feature.
I have also thought about checking if any relevant change has been made on DLFileEntry object in model listener method. I just wanted to check, if there is any configuration that could be made to bypass the onAfterUpdate method when it's triggered by incrementViewCounter method.
Any help is appreciated.
Update:
On after update method:
private void createMessage(DLFileEntry model, String create) {
JSONObject jsonObject = JSONFactoryUtil.createJSONObject();
jsonObject.put("action", create);
jsonObject.put("id", model.getFileEntryId());
MessageBusUtil.sendMessage(SUPIN_MESSAGE_LISTENER_DESTINATION, jsonObject);
}
#Override
public void onAfterUpdate(DLFileEntry model) throws ModelListenerException {
if (LOG.isTraceEnabled()) {
URL[] urls = ((URLClassLoader) (Thread.currentThread().getContextClassLoader())).getURLs();
LOG.trace("Current thread classpath is: " + StringUtils.join(urls, ","));
}
LogMF.info(LOG, "File entry on update event - id {0}" , new Object[]{model.getFileEntryId()});
Thread.dumpStack();
createMessage(model, UPDATE);
}
Here is the message listener (message bus) which performs the on after update actions:
private void createOrUpdate(DLFileEntry model, String createOrUpdate) {
try {
initPermissionChecker(model);
LOG.info("Document " + model.getFileEntryId() + " " + createOrUpdate + "d in Liferay. Creating entry in Safe.");
long documentInSafe;
if (UPDATE.equalsIgnoreCase(createOrUpdate)) {
documentInSafe = (long) model.getExpandoBridge().getAttribute(EXPANDO_SAFE_DOCUMENT_ID);
if (documentInSafe > 0) {
safeClient.updateDocumentInSafe(model);
} else {
documentInSafe = safeClient.createDocumentInSafe(model);
}
} else {
documentInSafe = safeClient.createDocumentInSafe(model);
}
LOG.info("Document " + createOrUpdate +"d successfully with id " + documentInSafe);
saveSafeIDToExpando(model, documentInSafe);
} catch (Exception e) {
LOG.error("Unable to safe ID of document in Safe", e);
}
}
private void saveSafeIDToExpando(DLFileEntry model, long documentInSafe) throws SystemException {
try {
ExpandoTable table = ExpandoTableLocalServiceUtil.getDefaultTable(model.getCompanyId(), DLFileEntry.class.getName());
ExpandoColumn column = ExpandoColumnLocalServiceUtil.getColumn(table.getTableId(), EXPANDO_SAFE_DOCUMENT_ID);
ExpandoValueLocalServiceUtil.addValue(model.getCompanyId(), table.getTableId(), column.getColumnId(), model.getClassPK(), String.valueOf(documentInSafe));
LOG.info("ID of document in Safe updated in expando attribute");
} catch (PortalException e) {
LOG.error("Unable to save Safe document ID in expando." , e);
;
}
}
private void initPermissionChecker(DLFileEntry model) throws Exception {
User safeAdminUser = UserLocalServiceUtil.getUserByScreenName(model.getCompanyId(), SAFE_ADMIN_SCREEN_NAME);
PermissionChecker permissionChecher = PermissionCheckerFactoryUtil.create(safeAdminUser);
PermissionThreadLocal.setPermissionChecker(permissionChecher);
PrincipalThreadLocal.setName(safeAdminUser.getUserId());
CompanyThreadLocal.setCompanyId(model.getCompanyId());
LOG.info("Permission checker successfully initialized.");
}
I suggest this, but I am not sure if it resolves your case.
I've changed the body of your own method onAfterUpdate.
Using TransactionCommitCallbackRegistryUtil you can detach the model update request from the subsequent createMessage logic.
public void onAfterUpdate(DLFileEntry model) throws ModelListenerException {
TransactionCommitCallbackRegistryUtil.registerCallback(new Callable() {
#Override
public Void call() throws Exception {
createMessage(model, UPDATE);
}
}

Null pointer exception on Initialize second controller class from first controller class

I am trying to access initialize method of another calss from a different class.But I am getting nullpointer Exception while returning ctroller
THis is the code I am trying to call from my second calss.
Line1- FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/src/myjavfxapp/controller/EditClientDetails.fxml"));
Line 2- EditClientDetailsController fooController = (EditClientDetailsController) fxmlLoader.getController();
Line3- fooController.initialize(null, null);
I am getting null pointer exception at line number 3.
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:75)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:279)
at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1435)
... 44 more
Caused by: java.lang.NullPointerException
at myjavfxapp.controller.NewUserController.saveNewuser(NewUserController.java:167)
... 54 more
My Intention is to initialize the "EditClientDetails.fxml" fields from different controller class.
Please point out if i missed anything.
Try the below example it working fine, you have to use load() function of FxmlLoader class.
public class Xxx extends Application {
#Override
public void start(Stage stage) throws Exception {
//Parent root = FXMLLoader.load(getClass().getResource("Sample.fxml"));
FXMLLoader loader = new FXMLLoader(getClass().getResource("Sample.fxml"));
Parent root = (Parent)loader.load();
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
SampleController controller = (SampleController)loader.getController();
}
public static void main(String[] args) {
launch(args);
}
}

rewriting a series in JavaFX linechart

I have a JavaFX app that utilizes the lineChart chart. I can write a chart to the app, and clear it, but when I want to write a new series and have it displayed, I get an error,
java.lang.IllegalArgumentException: Children: duplicate children added:
I understand the meaning, but not how to fix (I am very new to Java, let alone to FX).
Here is the relevant code from my controller (minus some class declarations):
(method called by the 'submit' button in chart tab window)
#FXML
private void getEngDataPlot(ActionEvent event) {
//check time inputs
boolean start = FieldVerifier.isValidUtcString(startRange.getText());
boolean end = FieldVerifier.isValidUtcString(endRange.getText());
type = engData.getValue().toString();
// Highlight errors.
startRangeMsg.setTextFill(Color.web(start ? "#000000" : "#ff0000"));
endRangeMsg.setTextFill(Color.web(end ? "#000000" : "#ff0000"));
if (!start || !end ) {
return;
}
// Save the preferences.
Preferences prefs = Preferences.userRoot().node(this.getClass().getName());
prefs.put("startRange", startRange.getText());
prefs.put("endRange", endRange.getText());
prefs.put("engData", engData.getValue().toString());
StringBuilder queryString = new StringBuilder();
queryString.append(String.format("edit out",
startRange.getText(),
endRange.getText()));
queryString.append(type);
log(queryString.toString());
// Start the query task.
submitEngData.setDisable(true);
// remove the old series.
engChart.getData().clear();
engDataProgressBar.setDisable(false);
engDataProgressBar.setProgress(-1.0);
//ProgressMessage.setText("Working...");
Thread t = new Thread(new EngDataPlotTask(queryString.toString()));
t.setDaemon(true);
t.start();
}
(the task called by above method:)
public EngDataPlotTask(String query) {
this.query = query;
}
#Override
protected Void call() {
try {
URL url = new URL(query);
String inputLine = null;
BufferedReader in = new BufferedReader(
new InputStreamReader(url.openStream()));
// while ( in.readLine() != null){
inputLine = in.readLine(); //}
Gson gson = new GsonBuilder().create();
DataObject[] dbin = gson.fromJson(inputLine, DataObject[].class);
in.close();
for (DataObject doa : dbin) {
series.getData().add(new XYChart.Data(doa.danTime, doa.Fvalue));
}
xAxis.setLabel("Dan Time (msec)");
} catch (Exception ex) {
log(ex.getLocalizedMessage());
}
Platform.runLater(new Runnable() {
#Override
public void run() {
submitEngData.setDisable(false);
// do some pretty stuff
String typeName = typeNameToTitle.get(type);
series.setName(typeName);
// put this series on the chart
engChart.getData().add(series);
engDataProgressBar.setDisable(true);
engDataProgressBar.setProgress(1.0);
}
});
return null;
}
}
The chart draws a first time, clears, and then the exception occurs. Requested stack trace follows:
Exception in runnable
java.lang.IllegalArgumentException: Children: duplicate children added: parent = Group#8922394[styleClass=plot-content]
at javafx.scene.Parent$1.onProposedChange(Unknown Source)
at com.sun.javafx.collections.VetoableObservableList.add(Unknown Source)
at com.sun.javafx.collections.ObservableListWrapper.add(Unknown Source)
at javafx.scene.chart.LineChart.seriesAdded(Unknown Source)
at javafx.scene.chart.XYChart$2.onChanged(Unknown Source)
at com.sun.javafx.collections.ListListenerHelper$SingleChange.fireValueChangedEvent(Unknown Source)
at com.sun.javafx.collections.ListListenerHelper.fireValueChangedEvent(Unknown Source)
at com.sun.javafx.collections.ObservableListWrapper.callObservers(Unknown Source)
at com.sun.javafx.collections.ObservableListWrapper.add(Unknown Source)
at com.sun.javafx.collections.ObservableListWrapper.add(Unknown Source)
at edu.arizona.lpl.dan.DanQueryToolFX.QueryToolController$EngDataPlotTask$1.run(QueryToolController.java:231)
at com.sun.javafx.application.PlatformImpl$4.run(Unknown Source)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.access$100(Unknown Source)
at com.sun.glass.ui.win.WinApplication$2$1.run(Unknown Source)
at java.lang.Thread.run(Thread.java:722)
Any ideas what I am doing wrong. I am a RANK NEWBIE, so please take that into account if you wish to reply. Thank you!
It took long time to find a workaround solution for this issue.
Please add below piece of code and test:
engChart.getData().retainAll();
engChart.getData().add(series);
My guess about the root cause according to your incomplete code is this line:
engChart.getData().add(series);
You should add series only once in initialize block for instance. But I think in your task thread, you are adding the already added same series again and having that mentioned exception. If your aim is to refresh the only series data, then just manipulate the series, getting it by engChart.getData().get(0); and delete that line in the code.
Once you add the series to the graph all you do is edit the series. Don't add it to the graph again.
The graph will follow whatever happens to the series i.e. just change the series data and the graph will automatically reflect the changes.

Powermock newbie/NoClassDefFoundError when mocking Apache DefaultHttpClient

I'm new to object mocking, and trying to create unit tests for some legacy code. I'm trying to use powermock for the first time, and encountering a NoClassDefFoundError on line 69 ( DefaultHttpClient mockClient = mock(DefaultHttpClient.class);) (see trace below).
Can anyone give me a hand and point me in the right direction?
#RunWith(PowerMockRunner.class)
#PrepareForTest(LoginClient.class)
public class LoginClientTest {
Properties props = null;
#Before
public void setUp() throws FileNotFoundException, IOException {
props = new Properties();
props.load(new FileInputStream("./src/test/resources/LoginClient/default.properties"));
}
/**
* Method description
* #throws Exception
*
*/
#Test
public void loginPositiveTest()
throws Exception {
DefaultHttpClient mockClient = mock(DefaultHttpClient.class);
HttpResponse mockResponse = mock(HttpResponse.class);
StatusLine mockStatusLine = mock(StatusLine.class);
Header[] headers = new BasicHeader[2];
headers[0] = new BasicHeader("Set-Cookie", "COOKIE-DATA");
headers[1] = new BasicHeader("Set-Cookie", "COOKIE-DATA-2");
whenNew(DefaultHttpClient.class).withNoArguments().thenReturn(mockClient);
when(mockClient.execute(isA(HttpUriRequest.class))).thenReturn(mockResponse);
when(mockResponse.getStatusLine()).thenReturn(mockStatusLine);
when(mockStatusLine.getStatusCode()).thenReturn(HttpStatus.SC_OK);
when(mockResponse.getAllHeaders()).thenReturn(headers);
LoginClient client = new LoginClient();
UsernamePasswordCredentials creds = new UsernamePasswordCredentials(props.getProperty("user"),
props.getProperty("password"));
String result = client.getCookie(creds.getUserName(), creds.getPassword());
System.out.println(result);
assertNotNull(result);
}
}
java.lang.NoClassDefFoundError: org.apache.http.impl.client.DefaultHttpClient$$EnhancerByMockitoWithCGLIB$$221fdb68
at sun.reflect.GeneratedSerializationConstructorAccessor6.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Constructor.java:521)
at org.objenesis.instantiator.sun.SunReflectionFactoryInstantiator.newInstance(SunReflectionFactoryInstantiator.java:40)
at org.objenesis.ObjenesisBase.newInstance(ObjenesisBase.java:59)
at org.mockito.internal.creation.jmock.ClassImposterizer.createProxy(ClassImposterizer.java:111)
at org.mockito.internal.creation.jmock.ClassImposterizer.imposterise(ClassImposterizer.java:51)
at org.powermock.api.mockito.internal.mockcreation.MockCreator.createMethodInvocationControl(MockCreator.java:100)
at org.powermock.api.mockito.internal.mockcreation.MockCreator.mock(MockCreator.java:58)
at org.powermock.api.mockito.PowerMockito.mock(PowerMockito.java:138)
at [REDACTED].clients.LoginClientTest.loginPositiveTest(LoginClientTest.java:61)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:615)
at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:66)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:307)
at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:86)
at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:94)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:294)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:112)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:73)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:282)
at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:84)
at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:49)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:207)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:146)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:120)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:118)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:102)
at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Problem appears to be solved by changing from java5 (IBM Websphere) to Sun/Oracle Java6.

Resources