"Uncaught ReferenceError: map is not defined" on swing app using jxbrowser - java

This is the code for showing map on swing application with jxbrowser. But when i click on the button, "Uncaught ReferenceError: map is not defined" this error is shown. The application is showing the map. But the joom in out and marker button does not working. What should i do?
final Browser browser = new Browser();
BrowserView view = new BrowserView(browser);
JButton zoomInButton = new JButton("Zoom In");
zoomInButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (zoomValue < MAX_ZOOM) {
browser.executeJavaScript("map.setZoom(" + ++zoomValue + ")");
}
}
});
JButton zoomOutButton = new JButton("Zoom Out");
zoomOutButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (zoomValue > MIN_ZOOM) {
browser.executeJavaScript("map.setZoom(" + --zoomValue + ")");
}
}
});
JButton setMarkerButton = new JButton("Set Marker");
setMarkerButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
browser.executeJavaScript("var myLatlng = new google.maps.LatLng(48.4431727,23.0488126);\n" +
"var marker = new google.maps.Marker({\n" +
" position: myLatlng,\n" +
" map: map,\n" +
" title: 'Hello World!'\n" +
"});");
}
});
JPanel toolBar = new JPanel();
toolBar.add(zoomInButton);
toolBar.add(zoomOutButton);
toolBar.add(setMarkerButton);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(view, BorderLayout.CENTER);
frame.add(toolBar, BorderLayout.SOUTH);
frame.setSize(900, 500);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
// Provide the correct full path to the map.html file, e.g. D:\\map.html
browser.loadURL("file:///E:/Programming/map.html");
and my map.html file:
<!DOCTYPE html>
<html>
<head>
<script src="http://maps.googleapis.com/maps/api/js"></script>
<script>
function initialize() {
var mapProp = {
center:new google.maps.LatLng(51.508742,-0.120850),
zoom:5,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById("googleMap"),mapProp);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="googleMap" style="width:850px;height:380px;"></div>
</body>
</html>

I suppose it happens because you didn't provide API_KEY for Google Maps API as described in the instruction at https://jxbrowser.support.teamdev.com/support/solutions/articles/9000012874-google-maps
Please replace the API_KEY string with your Google API KEY value:
https://maps.googleapis.com/maps/api/js?key=API_KEY&sensor=false

You cannot load the API once the page has already loaded.
google.maps.event.addDomListener(window, 'load', initialize);
You can check out some similar SO or this to get more guidance.

Related

How to get text from same Text Field used multiple times in Java Swing

I'm trying to get text from a JTextField iterated through my code (apparently, I can't add a different text field from a button). Here's what the "Add Items" button do:
addButton.addActionListener(new ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
tf = new JTextField("Name",20);
tfv = new JTextField("Value", 7);
p.revalidate();
p.repaint();
p.add(tf);
p.add(tfv);
}
});
It adds two new text fields in the panel using FlowLayout.
Now, I want to get the text given by the user from text fields with each one assigned to a different variable or maybe into an ArrayList by clickin the "OK" button but the getText() method doesn't seem to work.
okButton.addActionListener( e -> {
String txt = tfv.getText(); //only captures the text from the last field in the panel
});
Can't seem to think of anything right now.
in this code when you are reinitializing tf and tfv in addButton you lost the reference to previous defined textfiels
tf = new JTextField("Name",20);
tfv = new JTextField("Value", 7);
so to solve this problem you need to define an ArrayList to hold reference to all defined textfields and then you can access to all of them:
ArrayList<JTextField> arrayNames = new ArrayList<JTextField>();
ArrayList<JTextField> arrayValues = new ArrayList<JTextField>();
addButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
tf = new JTextField("Name",20);
tfv = new JTextField("Value", 7);
p.revalidate();
p.repaint();
p.add(tf);
p.add(tfv);
arrayNames.add(tf);
arrayValues.add(tfv);
}
});
accessing
okButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for (JTextField txtValue : arrayValues) {
System.out.println(txtValue.getText());
}
}
});
Method getComponents() will return all the components in p (the JPanel).
In order to distinguish each JTextField, you can either give each one a unique name via method setName() (and retrieve the name via method getName()) or set some property using method putClientProperty() (and retrieve the property via method getClientProperty()).
For example using setName() to set a unique name for each JTextField.
private int counter = 0; // class member
addButton.addActionListener(new ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
tf = new JTextField("Name",20);
tf.setName("tf" + counter);
tfv = new JTextField("Value", 7);
tfv.setName("tfv" + counter);
counter++;
p.revalidate();
p.repaint();
p.add(tf);
p.add(tfv);
}
});
How to identify each JTextField:
okButton.addActionListener( e -> {
Component[] cmpts = p.getComponents();
for (Component cmpt : cmpts) {
String name = cmpt.getName();
if (name.matches("^tf\\d+$") {
// Code to handle it.
}
else if (name.matches("^tfv\\d+$") {
// Handling code.
}
}
});

Reordering JRadioButtons

I'm creating a matching style game in java that displays a group of thumbnails which expand into picture with 3 radio buttons, 1 correct and 2 incorrect. Currently I have the 1st rb displaying the correct answer, it should be able to display on the second or 3rd but I can't figure out how to get it there.
So the possibilities would be (CII, ICI, or IIC)
(the rb text gets pulled from the filenames of the pictures)
final JTextArea textArea = new JTextArea();
add(textArea);
JRadioButton rb1 = new JRadioButton(rb1Text);
add(rb1);
rb1.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
textArea.setText("Correct");
}
});
JRadioButton rb2 = new JRadioButton(rb2Text);
add(rb2);
rb2.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
textArea.setText("Guess Again");
}
});
JRadioButton rb3 = new JRadioButton(rb3Text);
add(rb3);
rb3.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
textArea.setText("Guess Again");
}
});
ButtonGroup group = new ButtonGroup();
group.add(rb1);
group.add(rb2);
group.add(rb3);
Figured it out: I changed the setBounds to include a one of the 3 desired y values pulled from a shuffled collection.
ArrayList<String> obj = new ArrayList<String>();
obj.add("250");
obj.add("300");
obj.add("350");
Collections.shuffle(obj);
int rand1 = Integer.parseInt(obj.get(0));
int rand2 = Integer.parseInt(obj.get(1));
int rand3 = Integer.parseInt(obj.get(2));
rb1.setBounds(400, rand1, 200, 15);
rb2.setBounds(400, rand2, 200, 15);
rb3.setBounds(400, rand3, 200, 15);
So every time the next or previous button is pressed it puts the correct answer in a different spot.
Thanks for the ideas Hovercraft Full Of Eels!

WebView is not displaying correctly

The leftside is the html page loaded in Google Chrome and on the right side is the html page loaded in JavaFx WebView, The problem is that the navagation panel for Google Map is not displayed in the JavaFx WebView. Im using Java 7u79.
GoogleMap.java
webView = new WebView();
webEngine = webView.getEngine();
webEngine.getLoadWorker().stateProperty().addListener(new ChangeListener<State>(){
#Override
public void changed(ObservableValue<? extends State> ov, State t, State t1) {
System.out.println("STATE : " + t1);
if(t1.equals(State.SUCCEEDED)){
root.getChildren().remove(indicator);
}
}
});
indicator = new ProgressIndicator();
indicator.setMaxSize(40, 40);
String htmlcode = getFileContent("GoogleMap.html");
webEngine.loadContent(htmlcode);
root = new StackPane();
root.setAlignment(Pos.CENTER);
root.getChildren().add(webView);
root.getChildren().add(indicator);
Scene scene = new Scene(root, 550, 400);
primaryStage.setTitle("Google Map");
primaryStage.setScene(scene);
primaryStage.show();
GoogleMap.html
<!DOCTYPE html>
<html>
<head>
<script src="http://maps.googleapis.com/maps/api/js"></script>
<script>
function initialize() {
var mapProp = {
center : new google.maps.LatLng(51.508742,-0.120850),
zoom : 5,
mapTypeId : google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById("googleMap"),mapProp);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<style>
body
{
padding : 0;
margin : 0;
}
#googleMap
{
width : 550px;
height : 400px;
}
</style>
</head>
<body>
<div id="googleMap"></div>
</body>
</html>
I have all ok with it.
java 1.8.0_73 maybe you should try to update your java or get newer JavaFX?

How I set a OnClick event to <body> element in vaadin 7?

I need to "emulate" this:
document.getElementsByTagName("body")[0].onclick = function gameOver() { ...}
in vaadin 7, to display a dialog box when the user clicks anywhere on the web page
My code:
//...
#Override
protected void init(VaadinRequest request) {
Label labelH1 = new Label("<span style=\"color:SteelBlue;\">M</span>atching "
+ "<span style=\"color:Purple;\">G</span>ame!", ContentMode.HTML);
labelH1.setStyleName("h2");
Label labelH4 = new Label("Click on the extra smiling face on the <span>left</span>.",
ContentMode.HTML);
labelH4.setStyleName("h4");
CssLayout layout = new CssLayout();
AbsoluteLayout leftLayout = new AbsoluteLayout();
leftLayout.setId("leftSide");
AbsoluteLayout rightLayout = new AbsoluteLayout();
rightLayout.setId("rightSide");
layout.addComponent(labelH1);
layout.addComponent(labelH4);
layout.addComponent(leftLayout);
layout.addComponent(rightLayout);
setContent(layout);
}
You can use the click listener on the current UI. As following:
UI.getCurrent().addClickListener(new ClickListener()
{
#Override
public void click(com.vaadin.event.MouseEvents.ClickEvent event)
{
// You can show the dialouge box or any other of your desired task here ...!!!
System.out.println("UI is clicked");
}
});

Update one Wicket Panel from clicking an item in another Wicket Panel

I have looked at many update Panel answers in SO but could not solve my problem. It is very straight forward and I don't know why I dont get the panel updated.
I have two panel created in the RadioChoicePage.java:
public class RadioChoicePage extends ApplicationPageBase{
private static final long serialVersionUID = 1L;
public TestPanel tp;
public static TextPanel txp;
public RadioChoicePage(){
tp = new TestPanel("testPanel");
txp = new TextPanel("textPanel");
txp.setMsg("Before");
add(tp);
add(txp);
}
}
The markup file looks like the following:RadioChoicePage.html
<html xmlns:wicket="http://wicket.apache.org/dtds.data/wicket-xhtml1.4-strict.dtd" >
<body>
<wicket:extend>
<div wicket:id="testPanel" style="position:absolute; left:10px ; width:50%; z-index:10;">
</div>
<div wicket:id="textPanel" style="position:absolute; left:450px; width:50%; z-index:5">
</div>
</wicket:extend>
</body>
</html>
The two panel are TestPanel.java and TextPanel.java. I have a TestPanel.js file adding svg using d3.js and clicking on a circle I want to update the text panel.
I am able to call the wicket method from javascript and print that the circle was clicked on the console. But I am not able to update the text Panel.
Below is the code for TestPanel.java, TestPanel.html, TestPanel.js , TextPanel.java and TextPanel.html.
TestPanel.java
public class TestPanel extends Panel{
public static final JavaScriptResourceReference TEST_JS = new JavaScriptResourceReference(
TestPanel.class, "TestPanel.js");
TextPanel ttxp = new TextPanel("textPanel");
public TestPanel(String id) {
super(id);
final AbstractDefaultAjaxBehavior behave = new AbstractDefaultAjaxBehavior() {
private static final long serialVersionUID = 1L;
public void renderHead(Component component,IHeaderResponse aResponse){
super.renderHead(component, aResponse);
String componentMarkupId = component.getMarkupId();
String callbackUrl = getCallbackUrl().toString();
aResponse.render(JavaScriptReferenceHeaderItem.forReference(TEST_JS));
aResponse.render(JavaScriptReferenceHeaderItem.forReference(D3Reference.D3_JS));
aResponse.render(OnDomReadyHeaderItem.forScript("draw(" + componentMarkupId + ",\"" + callbackUrl + "\")"));
}
protected void respond(final AjaxRequestTarget target) {
//target.add(new Label("msg", "Yeah I was just called from Javascript!"));
System.out.println("I was succesfully clicked");
ttxp.setMsg("After");
target.add(ttxp);
}
};
add(behave);
}
}
TestPanel.html
<html xmlns:wicket="http://wicket.apache.org/dtds.data/wicket-xhtml1.4-strict.dtd" >
<head>
<wicket:head>
</wicket:head>
</head>
<body>
<wicket:panel>
<div id="chart" style="position:absolute; width:400px; height:400px; border:2px solid blue;"></div>
</wicket:panel>
</body>
</html>
TestPanel.js
function draw(componentMarkupId,callbackUrl){
console.log(" Draw is called!");
//Width and height
var w = 300;
var h = 100;
//Data
var dataset = [ 5, 10, 15, 20, 25 ];
//Create SVG element
var svg = d3.select("#chart")
.append("svg")
.attr("width", w)
.attr("height", h);
var circles = svg.selectAll("circle")
.data(dataset)
.enter()
.append("circle");
circles.attr("cx", function(d, i) {
return (i * 50) + 25;
})
.attr("cy", h/2)
.attr("r", function(d) {
return d;
})
.attr("fill", "red")
.attr("stroke", "orange")
.attr("stroke-width", function(d) {
return d/2;
});
circles.on("click",function(d){
this.style.stroke = "steelblue";
$(function() {
var wcall = Wicket.Ajax.get({ u:callbackUrl });
//var wcall = wicketAjaxGet('$callbackUrl$');
alert(wcall);
});
});
}
TextPanel.java
public class TextPanel extends Panel{
String msg;
boolean initialize = true;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public TextPanel(String id) {
super(id);
// TODO Auto-generated constructor stub
System.out.println(getMsg());
if(initialize){
setMsg("Before");
initialize = false;
}
Label mmsg = new Label("msg", getMsg());
add(mmsg);
setOutputMarkupId(true);
}
}
TextPanel.html
<html xmlns:wicket="http://wicket.apache.org/dtds.data/wicket-xhtml1.4-strict.dtd" >
<head>
<wicket:head>
</wicket:head>
</head>
<body>
<wicket:panel>
<div wicket:id="msg" style="border: 2px solid blue;"></div>
</wicket:panel>
</body>
</html>
Please do give me a solution with explanation. As I have read so many solutions and explanations on SO and other resources but I feel im missing something basic here.
You can copy the code exactly and run it to check whats the real problem. I do not get any errors but Panels simple dont get updated.
Thank you for taking time to read this huge question with a small problem.
RadioChoicePage's textPanel should not be static, otherwise the component will be shared between multiple sessions:
public TextPanel txp;
Why is TestPanel creating its own instance of TextPanel?
TextPanel ttxp = new TextPanel("textPanel");
Remove that! Add a hook method to TestPanel instead:
protected void onClicked(AjaxRequestTarget target) {
}
final AbstractDefaultAjaxBehavior behave = new AbstractDefaultAjaxBehavior() {
protected void respond(final AjaxRequestTarget target) {
onClicked(target);
}
}
Let RadioChoicePage decide what to do when anything is clicked:
tp = new TestPanel("testPanel") {
protected void onClicked(AjaxRequestTarget target) {
target.add(txp);
}
};
txp = new TextPanel("textPanel");
txp.setOutputMarkupId(true);

Categories

Resources