I am using JavaFX to embed browser. I am trying to run a javascript function addnum() from java class WebScale, but i am getting error.If i execute document.write() from webengine.executeScript() it is possible. But i cant call my function.
My code is as follow:
public class WebScale extends JApplet {
static ZoomingPane zoomingPane;
private static JFXPanel fxContainer;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
final JFrame frame = new JFrame("Area Configurator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JApplet applet = new WebScale();
applet.init();
frame.setContentPane(applet.getContentPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
applet.start();
frame.addComponentListener(new java.awt.event.ComponentAdapter() {
#Override
public void componentResized(java.awt.event.ComponentEvent evt) {
if (zoomingPane != null) {
zoomingPane.setZoomFactors((double)(frame.getWidth()/ 1280.0), (double)(frame.getHeight() / 800.0));
}
}
});
}
});
}
#Override
public void init() {
fxContainer = new JFXPanel();
fxContainer.setPreferredSize(new Dimension(800, 700));
add(fxContainer, BorderLayout.CENTER);
// create JavaFX scene
Platform.runLater(new Runnable() {
#Override
public void run() {
createScene();
}
});
}
private void createScene() {
WebView webView = new WebView();
zoomingPane = new ZoomingPane(webView);
BorderPane bp = new BorderPane();
bp.setCenter(zoomingPane);
fxContainer.setScene(new Scene(bp));
String strpath ;
strpath="file:///C:/Users/Priyanka/Desktop/FDASH/StationV3/Main.html";
final WebEngine engine = webView.getEngine();
engine.load(strpath);
engine.executeScript("addNum()");
}
private class ZoomingPane extends Pane {
Node content;
private final DoubleProperty zoomFactor = new SimpleDoubleProperty(1);
private double zoomFactory = 1.0;
private ZoomingPane(Node content) {
this.content = content;
getChildren().add(content);
final Scale scale = new Scale(1, 1);
content.getTransforms().add(scale);
zoomFactor.addListener(new ChangeListener<Number>() {
#Override
public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
scale.setX(newValue.doubleValue());
scale.setY(zoomFactory);
requestLayout();
}
});
}
#Override
protected void layoutChildren() {
Pos pos = Pos.TOP_LEFT;
double width = getWidth();
double height = getHeight();
double top = getInsets().getTop();
double right = getInsets().getRight();
double left = getInsets().getLeft();
double bottom = getInsets().getBottom();
double contentWidth = (width - left - right)/zoomFactor.get();
double contentHeight = (height - top - bottom)/zoomFactory;
layoutInArea(content, left, top,
contentWidth, contentHeight,
0, null,
pos.getHpos(),
pos.getVpos());
}
public final Double getZoomFactor() {
return zoomFactor.get();
}
public final void setZoomFactor(Double zoomFactor) {
this.zoomFactor.set(zoomFactor);
}
public final void setZoomFactors(Double zoomFactorx, Double Zoomfactory) {
this.zoomFactory = Zoomfactory;
this.zoomFactor.set(zoomFactorx);
}
public final DoubleProperty zoomFactorProperty() {
return zoomFactor;
}
}
}
I am getting the following error.
Exception in thread "JavaFX Application Thread" netscape.javascript.JSException: ReferenceError: Can't find variable: addNum
at com.sun.webkit.dom.JSObject.fwkMakeException(JSObject.java:128)
at com.sun.webkit.WebPage.twkExecuteScript(Native Method)
at com.sun.webkit.WebPage.executeScript(WebPage.java:1439)
at javafx.scene.web.WebEngine.executeScript(WebEngine.java:982)
at c.WebScale.createScene(WebScale.java:97)
at c.WebScale.access$0(WebScale.java:83)
at c.WebScale$2.run(WebScale.java:78)
at com.sun.javafx.application.PlatformImpl.lambda$null$174(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$175(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$149(WinApplication.java:191)
at java.lang.Thread.run(Thread.java:745)
Assuming addNum() is defined in Main.html, the javascript hasn't been loaded at the time that you're calling it. You should add a listener so you can call your javascript once the page is fully loaded:
final WebEngine engine = webView.getEngine();
engine.getLoadWorker().stateProperty().addListener(
new ChangeListener<State>() {
public void changed(ObservableValue ov, State oldState, State newState) {
if (newState == State.SUCCEEDED) {
engine.executeScript("addNum()");
}
}
});
engine.load(strpath);
Related
I have the following class in which I am trying to implement the prototype pattern:
public class Element extends Group implements Cloneable{
private final double ELEMENT_WIDTH = 50;
private final double ELEMENT_HEIGHT = 70;
private final double CIRCLE_RADIUS = 1;
private int minimalNumberOfInputs;
private Shape body = new Rectangle(ELEMENT_WIDTH, ELEMENT_HEIGHT, Color.WHITE);
private Circle output = new Circle(CIRCLE_RADIUS);
private Line outputLine = new Line(ELEMENT_WIDTH, ELEMENT_HEIGHT / 2, ELEMENT_WIDTH + 15, ELEMENT_HEIGHT / 2);
private ArrayList<Circle> inputs;
private ArrayList<Line> inputLines;
private Circle inversionDesignation;
private Text symbol;
private Integer identifier;
private double bodyCorX;
private double bodyCorY;
private double corX = 0;
private double corY = 0;
private double mouseX = 0;
private double mouseY = 0;
private boolean dragging = false;
public Integer getIdentifier() {
return identifier;
}
public ArrayList<Circle> getInputs() {
return inputs;
}
public Circle getOutput() {
return output;
}
public Circle getInversionDesignation() {
return inversionDesignation;
}
public double getELEMENT_WIDTH() {
return ELEMENT_WIDTH;
}
public double getELEMENT_HEIGHT() {
return ELEMENT_HEIGHT;
}
public double getCIRCLE_RADIUS() {
return CIRCLE_RADIUS;
}
public int getMinimalNumberOfInputs() {
return minimalNumberOfInputs;
}
public Shape getBody() {
return body;
}
public Line getOutputLine() {
return outputLine;
}
public ArrayList<Line> getInputLines() {
return inputLines;
}
public Text getSymbol() {
return symbol;
}
public double getBodyCorX() {
return bodyCorX;
}
public double getBodyCorY() {
return bodyCorY;
}
public double getCorX() {
return corX;
}
public double getCorY() {
return corY;
}
public double getMouseX() {
return mouseX;
}
public double getMouseY() {
return mouseY;
}
public boolean isDragging() {
return dragging;
}
public Element(){
}
public Element(Circle inversionDesignation, Text symbol, int minimalNumberOfInputs) {
this.minimalNumberOfInputs = minimalNumberOfInputs;
this.body.setStroke(Color.BLACK);
this.body.setStrokeType(StrokeType.INSIDE);
this.body.setStrokeWidth(2.5);
this.output.setFill(Color.BLACK);
this.output.toFront();
this.inversionDesignation = inversionDesignation;
this.symbol = symbol;
this.inputs = new ArrayList<>();
this.inputLines = new ArrayList<>();
this.identifier = this.hashCode();
this.outputLine.setStrokeWidth(2);
this.createStartInputs();
this.configureInputPoints();
this.bindGraphicalElements();
elementMovementEvents();
elementEnteredEvents();
}
private void bindGraphicalElements() {
this.getChildren().add(body);
this.getChildren().add(output);
this.getChildren().add(outputLine);
this.getChildren().addAll(inputs);
this.getChildren().addAll(inputLines);
if (this.symbol != null) {
this.getChildren().add(symbol);
symbol.relocate((ELEMENT_WIDTH / 2) - symbol.getTabSize() / 2, ELEMENT_HEIGHT / 8);
symbol.setFont(new Font("Consolas", 14));
}
if (this.inversionDesignation != null) {
this.getChildren().add(inversionDesignation);
this.inversionDesignation.setStrokeType(StrokeType.INSIDE);
this.inversionDesignation.setStrokeWidth(1);
this.inversionDesignation.setStroke(Color.BLACK);
this.inversionDesignation.relocate((this.bodyCorX + this.ELEMENT_WIDTH) - (this.inversionDesignation.getRadius() + 1), (this.bodyCorY + this.ELEMENT_HEIGHT / 2) - this.inversionDesignation.getRadius());
inversionDesignation.toFront();
}
}
private void addGraphicalElement(Shape shape) {
this.getChildren().add(shape);
}
private void createStartInputs() {
for (int i = 0; i < this.minimalNumberOfInputs; i++) {
inputs.add(new Circle(CIRCLE_RADIUS));
inputs.get(i).setFill(Color.BLACK);
inputs.get(i).toFront();
}
configureInputPoints();
for (int i = 0; i < inputs.size(); i++) {
Line line = new Line(inputs.get(i).getLayoutX() - 15, inputs.get(i).getLayoutY(), inputs.get(i).getLayoutX(), inputs.get(i).getLayoutY());
line.setStrokeWidth(2);
inputLines.add(line);
}
}
private void addNewInput() {
Circle newCircle = new Circle(CIRCLE_RADIUS);
newCircle.setFill(Color.BLACK);
this.inputs.add(newCircle);
this.configureInputPoints();
this.addGraphicalElement(newCircle);
}
private void configureInputPoints() {
this.output.relocate((this.bodyCorX + this.ELEMENT_WIDTH) - (output.getRadius() + 1), (this.bodyCorY + this.ELEMENT_HEIGHT / 2) - output.getRadius());
int distance = (int) ELEMENT_HEIGHT / (inputs.size() + 1); //Растояние между точками входа.
for (int i = 0; i < inputs.size(); i++) {
inputs.get(i).relocate(this.bodyCorX - (CIRCLE_RADIUS - 1), this.bodyCorY + (distance * (i + 1) - CIRCLE_RADIUS));
}
}
private void elementMovementEvents() {
onMousePressedProperty().set(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
mouseX = event.getSceneX();
mouseY = event.getSceneY();
corX = getLayoutX();
corY = getLayoutY();
}
});
onMouseDraggedProperty().set(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
double offsetX = event.getSceneX() - mouseX; //смещение по X
double offsetY = event.getSceneY() - mouseY;
corX += offsetX;
corY += offsetY;
double scaledX = corX;
double scaledY = corY;
setLayoutX(scaledX);
setLayoutY(scaledY);
dragging = true;
mouseX = event.getSceneX();
mouseY = event.getSceneY();
event.consume();
}
});
onMouseClickedProperty().set(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
dragging = false;
}
});
}
private void testEvent() {
this.addEventHandler(MouseEvent.MOUSE_CLICKED, event -> {
this.addNewInput();
});
}
private void elementEnteredEvents() {
onMouseClickedProperty().set(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
if (event.getTarget() instanceof Circle) {
System.out.println("Circle!");
}
}
});
}
#Override
public Element clone() throws CloneNotSupportedException{
return (Element)super.clone();
}
#Override
public String toString() {
return "Element " + this.hashCode() + ": location = " + this.getLayoutX() + ": output = " + this.minimalNumberOfInputs;
}
#Override
public boolean equals(Object obj) {
if(!(obj instanceof Element)) return false;
Element element = (Element) obj;
return element.getBodyCorX() == bodyCorX && element.getBodyCorY() == bodyCorY && element.getBody() == body;
}
}
I am trying to implement a pattern using the following method:
#Override
public Element clone() throws CloneNotSupportedException{
return (Element)super.clone();
}
I have a controller like this:
public class FXMLController {
#FXML
private AnchorPane anchorPane;
#FXML
private AnchorPane workPane;
//prototypes
private Element AndPrototype = new Element(null, new Text("&"), 2);
private Element OrPrototype = new Element(null, new Text("1"), 2);
private Element NotPrototype = new Element(new Circle(5, Color.WHITE), null, 1);
private Element AndNotPrototype = new Element(new Circle(5, Color.WHITE), new Text("&"), 2);
private Element OrNotPrototype = new Element(new Circle(5, Color.WHITE), new Text("1"), 2);
#FXML
public void initialize() {
}
#FXML
private void method() throws CloneNotSupportedException {
workPane.getChildren().add(AndPrototype.clone());
}
}
In this method, I am trying to make a clone and add it to the AnchorPane
#FXML
private void method() throws CloneNotSupportedException {
workPane.getChildren().add(AndPrototype.clone());
}
As a result, when I click on the button, I get an error of the following content:
Exception in thread "JavaFX Application Thread" java.lang.IndexOutOfBoundsException: Index -1 out of bounds for length 8
at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:266)
at java.base/java.util.Objects.checkIndex(Objects.java:359)
at java.base/java.util.ArrayList.get(ArrayList.java:427)
at javafx.base/com.sun.javafx.collections.ObservableListWrapper.get(ObservableListWrapper.java:89)
at javafx.base/com.sun.javafx.collections.VetoableListDecorator.get(VetoableListDecorator.java:305)
at javafx.graphics/javafx.scene.Parent.updateCachedBounds(Parent.java:1704)
at javafx.graphics/javafx.scene.Parent.recomputeBounds(Parent.java:1648)
at javafx.graphics/javafx.scene.Parent.doComputeGeomBounds(Parent.java:1501)
at javafx.graphics/javafx.scene.Parent$1.doComputeGeomBounds(Parent.java:115)
at javafx.graphics/com.sun.javafx.scene.ParentHelper.computeGeomBoundsImpl(ParentHelper.java:84)
at javafx.graphics/com.sun.javafx.scene.NodeHelper.computeGeomBounds(NodeHelper.java:115)
at javafx.graphics/javafx.scene.Node.updateGeomBounds(Node.java:3847)
at javafx.graphics/javafx.scene.Node.getGeomBounds(Node.java:3809)
at javafx.graphics/javafx.scene.Node.doComputeLayoutBounds(Node.java:3657)
at javafx.graphics/javafx.scene.Node$1.doComputeLayoutBounds(Node.java:449)
at javafx.graphics/com.sun.javafx.scene.NodeHelper.computeLayoutBoundsImpl(NodeHelper.java:166)
at javafx.graphics/com.sun.javafx.scene.GroupHelper.computeLayoutBoundsImpl(GroupHelper.java:63)
at javafx.graphics/com.sun.javafx.scene.NodeHelper.computeLayoutBounds(NodeHelper.java:106)
at javafx.graphics/javafx.scene.Node$13.computeBounds(Node.java:3509)
at javafx.graphics/javafx.scene.Node$LazyBoundsProperty.get(Node.java:9782)
at javafx.graphics/javafx.scene.Node$LazyBoundsProperty.get(Node.java:9752)
at javafx.graphics/javafx.scene.Node.getLayoutBounds(Node.java:3524)
at javafx.graphics/javafx.scene.layout.AnchorPane.computeWidth(AnchorPane.java:272)
at javafx.graphics/javafx.scene.layout.AnchorPane.computeMinWidth(AnchorPane.java:248)
at javafx.graphics/javafx.scene.Parent.minWidth(Parent.java:1048)
at javafx.graphics/javafx.scene.layout.Region.minWidth(Region.java:1553)
at javafx.graphics/javafx.scene.layout.Region.computeChildPrefAreaWidth(Region.java:2012)
at javafx.graphics/javafx.scene.layout.AnchorPane.computeChildWidth(AnchorPane.java:315)
at javafx.graphics/javafx.scene.layout.AnchorPane.layoutChildren(AnchorPane.java:353)
at javafx.graphics/javafx.scene.Parent.layout(Parent.java:1207)
at javafx.graphics/javafx.scene.Scene.doLayoutPass(Scene.java:576)
at javafx.graphics/javafx.scene.Scene$ScenePulseListener.pulse(Scene.java:2476)
at javafx.graphics/com.sun.javafx.tk.Toolkit.lambda$runPulse$2(Toolkit.java:413)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
at javafx.graphics/com.sun.javafx.tk.Toolkit.runPulse(Toolkit.java:412)
at javafx.graphics/com.sun.javafx.tk.Toolkit.firePulse(Toolkit.java:439)
at javafx.graphics/com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:563)
at javafx.graphics/com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:543)
at javafx.graphics/com.sun.javafx.tk.quantum.QuantumToolkit.pulseFromQueue(QuantumToolkit.java:536)
at javafx.graphics/com.sun.javafx.tk.quantum.QuantumToolkit.lambda$runToolkit$11(QuantumToolkit.java:342)
at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:174)
at java.base/java.lang.Thread.run(Thread.java:831)
I have absolutely no idea what this error may be connected with and in which direction they are moving.
Usually this is caused because you modified the scene graph or an attribute of a scene graph node off of the JavaFX thread.
Similar stack traces all caused by threading errors:
javafx vlcj play mutiple video get IndexOutOfBoundsException error
Exception on JavaFX when moving Labels around their container.(IndexOutOfBoundsException)
How to fix IndexOutOfBounds exception when javafx recomputes Parent/Node Bounds
How do I find out what's causing this Java FX Application Thread exception?
If it is a multi-threading issue, usually it can be fixed by either removing unnecessary threading. Or if multi-threading is unavoidable, using tools like the javafx.concurrent package or Platform.runLater to ensure nodes in the active scene graph are only modified on the JavaFX thread.
However, if you don’t have any multi-threading going on, it might be down to the weird cloning stuff you have going on which may be ill-advised. JavaFX nodes can only occur once in the scene and the clones may cause glitches in the framework.
i am customizing JavaFX TableView's header.
therefore i add a Graphic to the Label. By clicking the Label of the header i toggle my custom header(two lined). all this is working fine.
The header gets automatically resized so the custom headerfits in.
BUT, when i hide my custom headerthe headerstays large.
What am i missing so the headershrinks again?
i created a MCVE to demonstrate my problem:
public class TableViewHeaderMCVE extends Application {
private final TableView<Person> table = new TableView<>();
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage stage) {
final VBox root = new VBox();
Scene scene = new Scene(root);
stage.setWidth(218);
stage.setHeight(216);
TableColumn colName = new TableColumn("name");
colName.setMinWidth(100);
colName.setSortable(false);
TableColumn colProfession = new TableColumn("profession");
colProfession.setMinWidth(100);
colProfession.setSortable(false);
table.getColumns().addAll(colName, colProfession);
root.getChildren().addAll(table);
stage.setScene(scene);
stage.show();
// apply this after show!
TableViewHeader.installMod(table);
}
public static class TableViewHeader {
public static void installMod(TableView table) {
for (Node n : table.lookupAll(".column-header > .label")) {
if (n instanceof Label) {
new CustomHeaderLabel((Label) n);
}
}
}
}
public static class CustomHeaderLabel extends BorderPane {
protected Label customNode = null;
BooleanProperty expanded = new SimpleBooleanProperty(this, "expanded", false);
public CustomHeaderLabel(final Label parent) {
Label label = new Label(parent.getText());
// custom MenuButton
Button btn = new Button();
btn.setGraphic(new Label("\u2261"));
btn.setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent ae) {
System.out.println("Hello World");
}
});
TextField filterTextField = new TextField();
filterTextField.promptTextProperty().set("type here to filter");
setCenter(label);
setRight(btn);
setBottom(filterTextField);
EventHandler<MouseEvent> toggleHeader = new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent me) {
expanded.set(!expanded.get());
}
};
parent.setOnMouseClicked(toggleHeader);
expanded.addListener(new ChangeListener<Boolean>() {
#Override
public void changed(ObservableValue<? extends Boolean> obs, Boolean oldValue, Boolean value) {
showCustomHeader(value);
}
});
label.textProperty().bind(parent.textProperty());
parent.setGraphic(this);
customNode = parent;
showCustomHeader(expanded.get());
}
protected void showCustomHeader(Boolean value) {
if (value) {
customNode.setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
} else {
customNode.setContentDisplay(ContentDisplay.TEXT_ONLY);
}
}
}
public static class Person {
private final SimpleStringProperty name;
private final SimpleStringProperty profession;
private Person(String name, String profession) {
this.name = new SimpleStringProperty(name);
this.profession = new SimpleStringProperty(profession);
}
public String getName() {
return name.get();
}
public String getProfession() {
return profession.get();
}
}
}
thanks to #James_D for his reply.
after his reply i tested the code on another computer
works on:
JDK 1.8.0_161 on Windows 10
JDK 9.0.4 and JDK 10 on Mac OS X
fails on:
JDK 1.8.0_66-b18 on Windows 7
I am trying to make an app that which is like a place picker, meaning you write down a product like pizza or burger, and u get all the places around you that have pizza or burger.
now I'm using RecyclerView in my fragment and i also have Map fragment
when you click on an item in the RV, it will show its location on the map using the map fragment.
my problem is when I'm clicking on an item in the recyclerview i get nullpointerexception
here is my code of the first fragment
public class PlacesFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> , AdapterView.OnItemClickListener{
ClickListener listener;
static Places places;
PlacesAdapter adapter;
public FragmentManager fm;
MyMapFragment mapFragment;
Cursor cursor;
public PlacesFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View myFragView= inflater.inflate(R.layout.fragment_places, container, false);
RecyclerView rv= (RecyclerView)myFragView.findViewById(R.id.placesRecyclerView);
//this create the line beetween every list to do so i have import to the build gradle a flexible divider
rv.addItemDecoration(new HorizontalDividerItemDecoration.Builder(getActivity()).color(Color.BLACK).build());
cursor = getActivity().getContentResolver().query(CONTENT_URI, null, null, null, null);
adapter= new PlacesAdapter(cursor, getActivity());
rv.setAdapter(adapter);
adapter.notifyItemRangeChanged(cursor.getPosition(), cursor.getCount());
adapter.notifyDataSetChanged();
rv.setLayoutManager(new LinearLayoutManager(getActivity()));
rv.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), rv, new ClickListener() {
#Override
public void onPlaceClick(String latlng) {
//when i click on a place it will go to the map fragment
// Toast.makeText(getActivity(), "on click" + position, Toast.LENGTH_LONG).show();
/* FragmentManager fm = getFragmentManager();
// get the map object from the fragment:
mapFragment = MyMapFragment.newInstance(places);
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.fragmantContainer, mapFragment, "map");
ft.addToBackStack(null);
ft.commit();*/
}
})
);
// getLoaderManager().initLoader(1, null,);
return myFragView;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
listener = (ClickListener)context;
} catch (ClassCastException e) {
throw new ClassCastException("context " + context.toString()
+ "must implement PlacesFragmantListener!");
}
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// CursorLoader c=getContext().getContentResolver().query(PlacesContract.Places.CONTENT_URI, null, null,null, null);
return new CursorLoader(getActivity(),CONTENT_URI, null, null,null, null );
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
public static interface PlacesFragmantListener {
public void onLocationSelected(Places places);
}
class RecyclerTouchListener implements RecyclerView.OnItemTouchListener{
private GestureDetector gestureDetector;
private ClickListener clickListener;
MyMapFragment mapFragment;
public RecyclerTouchListener(Context context, RecyclerView recyclerView, ClickListener clickListener){
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener(){
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
super.onLongPress(e);
}
});
this.clickListener = clickListener;
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(),e.getY());
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
Log.d("PlaceAdapter", "onTouchEvent"+e);
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
}
here is my map fragment
public class MyMapFragment extends Fragment {
public MyMapFragment(){
}
public static MyMapFragment newInstance(Places places) {}
if (places == null) {
places = new Places(0,"no Location selected","","", "");
}
// the arguments to pass
Bundle args = new Bundle();
args.putString("location", places.getLocation());
args.putDouble("lat", location.getLat());
args.putDouble("lon", location.getLon());
MyMapFragment mapFragmant = new MyMapFragment();
mapFragmant.setArguments(args);
return mapFragmant;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.mapfragment, container, false);
Bundle b=getArguments();
String latlng= b.getString("location");
Log.d("fragment...", latlng);
String[] latlongarr= latlng.split(",");
double lat= Double.parseDouble(latlongarr[0]);
double lon= Double.parseDouble(latlongarr[1]);
FragmentManager fm = getFragmentManager();
MapFragment mapFragment = (MapFragment) fm.findFragmentById(R.id.map);
// get the map object from the fragment:
GoogleMap map = mapFragment.getMap();
if(map!= null) {
// setup the map type:
map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
// setup map position and zoom
LatLng position = new LatLng(b.getDouble("lat"), b.getDouble("lon"));
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(position, 15);
map.moveCamera(update);
}
return view;
}
}
here is my adapter
public class PlacesAdapter extends RecyclerView.Adapter<PlacesAdapter.PlaceHolder> {
private Cursor cursor;
private Context context;
private static TextView placeName, address, distance, url;
public static ImageView imgplace;
public static PlaceHolder.ClickListener clickListener;
private static Places place;
private DataSetObserver mDataSetObserver;
MyMapFragment mapFragment;
private boolean mDataValid;
ClickListener listener;
public PlacesAdapter(Cursor cursor, Context context) {
this.context = context;
this.cursor = cursor;
mDataSetObserver = new NotifyingDataSetObserver();
if (cursor != null) {
cursor.registerDataSetObserver(mDataSetObserver);
}
}
#Override
public PlaceHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// cursor.setNotificationUri(context.getContentResolver(), CONTENT_URI);
LayoutInflater inflater = LayoutInflater.from(context);
View myView = inflater.inflate(R.layout.single_place, parent, false);
PlaceHolder placeHolder = new PlaceHolder(myView, new PlaceHolder.PlacesFragmantListener() {
#Override
public void onLocationSelected(Places places) {
}
});
return placeHolder;
}
#Override
public void setHasStableIds(boolean hasStableIds) {
super.setHasStableIds(true);
}
#Override
public void onBindViewHolder(PlacesAdapter.PlaceHolder holder, final int position) {
if (cursor.moveToPosition(position)) {
int column_number = cursor.getColumnIndex(PLACES_NAME);
String name = cursor.getString(column_number);
placeName.setText(name);
int column_number2 = cursor.getColumnIndex(PLACES_ADDRESS);
String adr = cursor.getString(column_number2);
address.setText(adr);
int column_number3 = cursor.getColumnIndex(PLACES_DISTANEC);
String dis = cursor.getString(column_number3);
distance.setText(dis);
int column_number4 = cursor.getColumnIndex(PLACE_PHOTO);
String photo = cursor.getString(column_number4);
if(!photo.equals(""))
{
GoogleAccess.myImageDownloader loader= new GoogleAccess.myImageDownloader(imgplace);
loader.execute(photo);
}
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "Item click at " + position, Toast.LENGTH_LONG).show();
if(cursor.moveToPosition(position))
{
String latlong= cursor.getString(cursor.getColumnIndex(PlacesDbconstanst.CurrentPlaces.PLACES_DISTANEC));
listener.onPlaceClick(latlong);
}
}
});
}
public void setClickListener(PlaceHolder.ClickListener clickListener){
this.clickListener = clickListener;
}
#Override
public int getItemCount() {
return cursor.getCount();
}
public static class PlaceHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
PlacesFragmantListener listener;
public PlaceHolder(View itemView, PlacesFragmantListener placesFragmantListener) {
super(itemView);
listener = placesFragmantListener;
placeName = (TextView) itemView.findViewById(R.id.placeNametextView);
address = (TextView) itemView.findViewById(R.id.addressTextView);
distance = (TextView) itemView.findViewById(R.id.distanceTextView);
imgplace = (ImageView) itemView.findViewById(R.id.placesImageViewId);
imgplace.setOnClickListener(this);
itemView.setOnClickListener(this);
}
RecyclerView rv;
#Override
public void onClick(View v) {
if(clickListener!=null){
clickListener.itemClicked(v, getPosition());
}
}
public static interface PlacesFragmantListener {
void onLocationSelected(Places places);
}
public interface ClickListener{
public void itemClicked (View view, int position);
}
}
private class NotifyingDataSetObserver extends DataSetObserver {
#Override
public void onChanged() {
super.onChanged();
mDataValid = true;
notifyDataSetChanged();
}
#Override
public void onInvalidated() {
super.onInvalidated();
mDataValid = false;
notifyDataSetChanged();
}
}
}
can you tell me what i did wrong
here is the log comment
03-30 04:55:28.042 2318-2318/com.myapps.pinkas.placesofintrest W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0xa4c8cb20)
03-30 04:55:28.042 2318-2318/com.myapps.pinkas.placesofintrest E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.myapps.pinkas.placesofintrest, PID: 2318
java.lang.NullPointerException
at com.myapps.pinkas.placesofintrest.PlacesAdapter$2.onClick(PlacesAdapter.java:112)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
distance = (TextView) itemView.findViewById(R.id.distanceTextView);
is this line come in 112 in your class file, it's seems like, you have not defined view id or view in XML, please check line number 112 in PlacesAdapter.class
Problem 1: Setting onclick listener twice. In onbindviewholder you have put holder.itemView.setOnclicklistener and then again in static class viewholder, you have put itemview.setOnclickListener. When you assign setOnclicklistener inside the static viewholder class, it means it will behave in a particular way uninfluenced by values present in any other views (like textview, imageview) or any such factors which depend on some 'value' property of the views. For most purposes you should have setOnClicklistener onto the itemview/textview/etc inside the static viewholder class which in your case is called placeholder.
Problem 2: Here is the reason why I believe you are getting NullPointerException. onbindviewholder has access to only the views declared in static viewholder class. If you want itemview to be accessible to onbindviewholder then make the following changes:
public static class PlaceHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
PlacesFragmantListener listener;
View iv;
public PlaceHolder(View itemView, PlacesFragmantListener placesFragmantListener) {
super(itemView);
iv = (View)itemView;
//then rest of the code
Now in your onbindviewholder write the following instead of holder.itemview.setonclicklistener
holder.iv.setonclicklistener...
Problem 3: in your static viewholder, you have put:
imgplace.setOnClickListener(this);
itemView.setOnClickListener(this);
itemview is the layout in which imgplace exists. And you have setonclicklistener on both of them. This is like putting a button on a button. It makes no sense. I think this will lead you into lot of mess. For some reason you want both to perform the same function on being clicked (you have put 'this' inside setOnClickListener). This is completely illogical. So set the clicklistener to either imgplace or itemview but not both
I cant get this to resize, it always go for the preferred size for each screen. This is not ideal for a full screen application. It bascially just becomes a little box in the top left corner =(
I've spent days on this now but cant get it to work.
Could anyone tell me what im doing wrong? thanks
Main class:
public class Main extends Application {
public static final String MAIN_SCREEN = "main";
public static final String MAIN_SCREEN_FXML = "../gui/main.fxml";
public static final String CUSTOMER_SCREEN = "customer_main";
public static final String CUSTOMER_SCREEN_FXML = "../gui/customer_main.fxml";
#Override
public void start(Stage primaryStage) {
primaryStage.setFullScreen(true);
primaryStage.centerOnScreen();
ScreensController mainContainer = new ScreensController();
mainContainer.loadScreen(Main.MAIN_SCREEN,
Main.MAIN_SCREEN_FXML);
mainContainer.loadScreen(Main.CUSTOMER_SCREEN,
Main.CUSTOMER_SCREEN_FXML);
mainContainer.setScreen(Main.MAIN_SCREEN);
Group root = new Group();
root.getChildren().addAll(mainContainer);
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.show();
mainContainer.requestLayout();
}
public static void main(String[] args) {
launch(args);
}
First screen controller class (has FXML file):
public class MainScreenController implements ControlledScreen, Initializable{
ScreensController myController;
#FXML
private VBox mainScreen;
#FXML
private void mainScreenClicked(){
myController.setScreen(Main.CUSTOMER_SCREEN);
}
#Override
public void initialize(URL arg0, ResourceBundle arg1) {
}
#Override
public void setScreenParent(ScreensController screenParent) {
myController = screenParent;
}
Stack pane for a nice layout:
public class ScreensController extends StackPane {
public ScreensController(){
}
private HashMap<String, Node> screens = new HashMap<>();
public void addScreen(String name, Node screen) {
screens.put(name, screen);
}
public boolean loadScreen(String name, String resource) {
try {
FXMLLoader myLoader = new FXMLLoader(getClass().getResource(resource));
Parent loadScreen = (Parent) myLoader.load();
ControlledScreen myScreenControler =
((ControlledScreen) myLoader.getController());
myScreenControler.setScreenParent(this);
addScreen(name, loadScreen);
return true;
}catch(Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
return false;
}
}
public boolean setScreen(final String name) {
if(screens.get(name) != null) { //screen loaded
final DoubleProperty opacity = opacityProperty();
//Is there is more than one screen
if(!getChildren().isEmpty()){
Timeline fade = new Timeline(
new KeyFrame(Duration.ZERO,
new KeyValue(opacity,1.0)),
new KeyFrame(new Duration(1000),
new EventHandler() {
#Override
public void handle(Event t) {
//remove displayed screen
getChildren().remove(0);
//add new screen
getChildren().add(0, screens.get(name));
Timeline fadeIn = new Timeline(
new KeyFrame(Duration.ZERO,
new KeyValue(opacity, 0.0)),
new KeyFrame(new Duration(800),
new KeyValue(opacity, 1.0)));
fadeIn.play();
}
}, new KeyValue(opacity, 0.0)));
fade.play();
} else {
//no one else been displayed, then just show
setOpacity(0.0);
getChildren().add(screens.get(name));
Timeline fadeIn = new Timeline(
new KeyFrame(Duration.ZERO,
new KeyValue(opacity, 0.0)),
new KeyFrame(new Duration(2500),
new KeyValue(opacity, 1.0)));
fadeIn.play();
}
return true;
} else {
System.out.println("screen hasn't been loaded!\n");
return false;
}
}
public boolean unloadScreen(String name) {
if(screens.remove(name) == null) {
System.out.println("Screen didn't exist");
return false;
} else {
return true;
}
}
}
interface so that each screen knows its parent:
public interface ControlledScreen {
public void setScreenParent(ScreensController screenPage);
}
Second controller class to verify that the stackpane works (has FXML file):
public class CustomerMenuController implements ControlledScreen, Initializable {
ScreensController myController;
#FXML
private FlowPane customerMenuFlow;
#Override
public void initialize(URL location, ResourceBundle resources) {
for (int i = 0; i < 3;i++){
new Customer();
}
Button [] menuButtons = new Button[Customer.customers.size()];
for (int i = 0; i < Customer.customers.size();i++){
menuButtons[i] = new Button("Customer " + i);
customerMenuFlow.getChildren().add(menuButtons[i]);
}
}
#Override
public void setScreenParent(ScreensController screenParent) {
myController = screenParent;
}
}
You shouldn't use primaryStage.setFullScreen(true); for resizable applications. Not in this context anyway. Once you remove that line, the application will start with its preferred size, but then the user is able to drag the corners of the window to resize the application.
I have a problem with my current libGDX project.
The game starts with a main menu, where you can click on two buttons. After starting the game, you can pause it through Esc and get to the pause screen, which is very similar to the main menu.
I don't know why, but the buttons in the pause screen are not clickable.
Here is the code of the game screen with the problem:
public class GameScreen implements Screen{
private Texture[] monsterTextures = {Assets.manager.get(("Ressources/DemonHunter.jpg"), Texture.class), Assets.manager.get(("Ressources/WingedDemon.jpg"), Texture.class),
Assets.manager.get(("Ressources/Viking.jpg"), Texture.class), Assets.manager.get(("Ressources/DemonWarrior.jpg"), Texture.class)};
private Image[] monsterImages = {new Image(monsterTextures[0]), new Image(monsterTextures[1]), new Image(monsterTextures[2]), new Image(monsterTextures[3])};
private Stage gameStage = new Stage(), pauseStage = new Stage();
private Table table = new Table();
private Skin menuSkin = Assets.menuSkin;
private TextButton buttonContinue = new TextButton("Continue", menuSkin),
buttonExit = new TextButton("Exit", menuSkin);
private Label title = new Label ("Game", menuSkin);
private int randomMonster;
private int currentMonsterLife = 1 + (int)(Math.random() * ((5-1) + 1));
public static final int GAME_CREATING = 0;
public static final int GAME_RUNNING = 1;
public static final int GAME_PAUSED = 2;
private int gamestatus = 0;
#Override
public void show() {
randomMonster = 0 + (int)(Math.random() * ((3-0) + 1));
gameStage.addActor(monsterImages[randomMonster]);
}
public void newMonster() {
monsterImages[randomMonster].remove();
Gdx.gl.glClearColor(0,0,0,1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
randomMonster = 0 + (int)(Math.random() * ((3-0) + 1));
currentMonsterLife = 1 + (int)(Math.random() * ((5-1) + 1));
gameStage.addActor(monsterImages[randomMonster]);
}
#Override
public void render(float delta) {
if(Gdx.input.isKeyJustPressed(Keys.ESCAPE)) pauseGame();
if(gamestatus == GAME_CREATING) {
buttonContinue.addListener(new ClickListener(){
public void clicked(InputEvent event, float x, float y) {
Gdx.gl.glClearColor(0,0,0,1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
gamestatus = GAME_RUNNING;
}
});
buttonExit.addListener(new ClickListener(){
public void clicked(InputEvent event, float x, float y) {
Gdx.app.exit();
}
});
table.add(title).padBottom(40).row();
table.add(buttonContinue).size(150, 60).padBottom(20).row();
table.add(buttonExit).size(150, 60).padBottom(20).row();
table.setFillParent(true);
pauseStage.addActor(table);
Gdx.input.setInputProcessor(pauseStage);
Gdx.input.setInputProcessor(gameStage);
gamestatus = GAME_RUNNING;
}
if(gamestatus == GAME_RUNNING) {
Gdx.gl.glClearColor(0,0,0,1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
gameStage.act();
gameStage.draw();
if(Gdx.input.justTouched())currentMonsterLife -= 1;
if(currentMonsterLife == 0)newMonster();
}
if(gamestatus == GAME_PAUSED) {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
pauseStage.act();
pauseStage.draw();
}
}
public void pauseGame() {
gamestatus = GAME_PAUSED;
}
#Override
public void resize(int width, int height) {
// TODO Auto-generated method stub
}
#Override
public void pause() {
pauseGame();
}
#Override
public void resume() {
// TODO Auto-generated method stub
}
#Override
public void hide() {
// TODO Auto-generated method stub
}
#Override
public void dispose() {
for(int i = 0; i < monsterTextures.length; i++) {
monsterTextures[i].dispose();
}
gameStage.dispose();
pauseStage.dispose();
menuSkin.dispose();
}
}
And here is the code of the main menu, where the buttons are working:
public class MainMenu implements Screen {
private Stage stage = new Stage();
private Table table = new Table();
private Skin menuSkin = Assets.menuSkin;
private TextButton buttonPlay = new TextButton("Play", menuSkin),
buttonExit = new TextButton("Exit", menuSkin);
private Label title = new Label ("Hunt for Power", menuSkin);
#Override
public void render(float delta) {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
stage.act();
stage.draw();
}
#Override
public void show() {
buttonPlay.addListener(new ClickListener(){
public void clicked(InputEvent event, float x, float y) {
((Game)Gdx.app.getApplicationListener()).setScreen(new GameScreen());
}
});
buttonExit.addListener(new ClickListener(){
public void clicked(InputEvent event, float x, float y) {
Gdx.app.exit();
}
});
table.add(title).padBottom(40).row();
table.add(buttonPlay).size(150, 60).padBottom(20).row();
table.add(buttonExit).size(150, 60).padBottom(20).row();
table.setFillParent(true);
stage.addActor(table);
Gdx.input.setInputProcessor(stage);
}
#Override
public void resize(int width, int height) {
// TODO Auto-generated method stub
}
#Override
public void pause() {
// TODO Auto-generated method stub
}
#Override
public void resume() {
// TODO Auto-generated method stub
}
#Override
public void hide() {
dispose();
}
#Override
public void dispose() {
stage.dispose();
}
}
I really hope someone is able to find the solution to this.
Greetings, Joshflux
There is something weird with how you set the InputProcessor:
in the show() method you set the Stage stage as the InputProcessor:
Gdx.input.setInputProcessor(stage);
so far so good, but in the render() method you set it to different stages than the one where your buttons are!
Gdx.input.setInputProcessor(pauseStage);
Gdx.input.setInputProcessor(gameStage);
==> remove this code from the render method! Also you should not have the other code that looks like it should only be executed when creating the screen inside the render() method. It seems like your code results in overlapping stages, buttons & tables and it is unclear which stage currently is set as InputProcessor.
Like #donfuxx said, you should not set your input processor in the render() method, but rather in show().
And you can only set one input processor at a time. Your second call to setInputProcessor replaces the first call. If you want two different stages as input processors, you must combine them with an InputMultiplexer:
public void show(){
Gdx.input.setInputProcessor(new InputMultiplexer(pauseStage, gameStage)); //list them in order of precedence
//...your other code
}