Binding a JavaFX variable to a Java class instance variable
Hi,
I am pretty new to JavaFX but have been developing in Java for many years. I am trying to develop a JavaFX webservice client. What I am doing is creating a basic scene that displays the data values that I am polling with a Java class that extends Thread. The Java class is reading temperature and voltage from a remote server and storing the response in an instance variable. I would like to bind a JavaFx variable to the Java class instance variable so that I can display the values whenever they change.
var conn: WebserviceConnection; // Java class that extends Thread
var response: WebserviceResponse;
try {
conn = new WebserviceConnection("some_url");
conn.start();
Thread.sleep(10000);
} catch (e:Exception) {
e.printStackTrace();
def bindTemp = bind conn.getResponse().getTemperature();
def bindVolt = bind conn.getResponse().getVoltage();
The WebserviceConnection class is opening a socket connection and reading some data in a separate thread. A regular socket connection is used because the server is not using HTTP.
When I run the application, the bindTemp and bindVolt are not updated whenever new data values are received.
Am I missing something with how bind works? Can I do what I want to do with 'bind'. I basically want to run a separate thread to retrieve data and want my UI to be updated when the data changes.
Is there a better way to do this than the way I am trying to do it?
Thanks for any help in advance.
-Richard
Hi,
If you don't want to constantly poll for value change, you can use the observer design pattern, but you need to modify the classes that serve the values to javafx.
Heres a simple example:
The Thread which updates a value in every second:
// TimeServer.java
public class TimeServer extends Thread {
private boolean interrupted = false;
public ValueObject valueObject = new ValueObject();
@Override
public void run() {
while (!interrupted) {
try {
valueObject.setValue(Long.toString(System.currentTimeMillis()));
sleep(1000);
} catch (InterruptedException ex) {
interrupted = true;
}The ValueObject class which contains the values we want to bind in javafx:
// ValueObject.java
import java.util.Observable;
public class ValueObject extends Observable {
private String value;
public String getValue() {
return this.value;
public void setValue(String value) {
this.value = value;
fireNotify();
private void fireNotify() {
setChanged();
notifyObservers();
}We also need an adapter class in JFX so we can use bind:
// ValueObjectAdapter.fx
import java.util.Observer;
import java.util.Observable;
public class ValueObjectAdapter extends Observer {
public-read var value : String;
public var valueObject : ValueObject
on replace { valueObject.addObserver(this)}
override function update(observable: Observable, arg: Object) {
// We need to run every code in the JFX EDT
// do not change if the update method can be called outside the Event Dispatch Thread!
FX.deferAction(
function(): Void {
value = valueObject.getValue();
}And finally the main JFX code which displays the canging value:
// Main.fx
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.text.Text;
import javafx.scene.text.Font;
import threadbindfx.TimeServer;
var timeServer : TimeServer;
var valueObjectAdapter : ValueObjectAdapter = new ValueObjectAdapter();
timeServer = new TimeServer();
valueObjectAdapter.valueObject = timeServer.valueObject;
timeServer.start();
Stage {
title: "Time Application"
width: 250
height: 80
scene: Scene {
content: Text {
font : Font {
size : 24
x : 10, y : 30
content: bind valueObjectAdapter.value;
}This approach uses less cpu time than constant polling, and changes aren't dependent on the polling interval.
However this cannot be applied to code which you cannot change obviously.
I hope this helps.
Similar Messages
-
Why does a variable set in java class appear null in message body
Hello,
I set my variable in the java class like this:
DocumentProcessor dp = new DocumentProcessor(
control_file, path, working_dir );
Properties prop = new Properties();
prop.put( "user-variable:XMLPUB_BODY_VAR", "from_email" );
dp.setConfig(prop);
dp.process();
and in the control file like this:
<xapi:message id="123" to="${C_EMAIL_ADDR}" attachment="true" content_type="html/text" subject="Remittance Advice for check#${C_CHECK_NUM} ">Hello,
Attached is the remittance advice: #${C_CHECK_NUM}
If you have any queries, please send an email to: ${XMLPUB_BODY_VAR}
The problem is that he XMLPUB_BODY_VAR appears null. Is this a know problem? Any solutions?does anyone know of this bug? I've heard similar problems before where some of the variables in the email content don't mysteriously get replaced.
Is this a known bug? -
Using java class and variables declared in java file in jsp
hi everyone
i m trying to seperate business logic form web layer. i don't know i am doing in a right way or not.
i wanted to access my own java class and its variables in jsp.
for this i created java file like this
package ris;
import java.sql.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class NewClass{
public static void main(String args[]){
Connection con = null;
ResultSet rs=null;
Statement smt=null;
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
con=DriverManager.getConnection("jdbc:mysql:///net","root", "anthony111");
smt=con.createStatement();
rs= smt.executeQuery("SELECT * FROM emp");
while(rs.next()){
String str = rs.getString("Name");
}catch( Exception e){
String msg="Exception:"+e.getMessage();
}finally {
try {
if(con != null)
con.close();
} catch(SQLException e) {}
}next i created a jsp where i want to access String str defined in java class above.
<%--
Document : fisrt
Created on : Jul 25, 2009, 3:00:38 PM
Author : REiSHI
--%>
<%@page import="ris.NewClass"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1><%=str%></h1>
</body>
</html>I wanted to print the name field extracted from database by ResultSet.
but it gives error cannot find symbol str.
please help me to find right way to do this.
i am using netbeans ide.Very bad approach
1) Think if your table contains more than one NAMEs then you will get only the last one with your code.
2) Your String is declared as local variable in the method.
3) You have not created any object of NewClass nor called the method in JSP page. Then who will call the method to run sql?
4) Your NewClass contains main method which will not work in web application, it's not standalone desktop application so remove main.
Better create an ArrayList and then call the method of NewClass and then store the data into ArrayList and return the ArrayList.
It should look like
{code:java}
package ris;
import java.sql.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class NewClass{
public static ArrayList getNames(){
Connection con = null;
ResultSet rs=null;
Statement smt=null;
ArrayList nameList = new ArrayList();
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
con=DriverManager.getConnection("jdbc:mysql:///net","root", "anthony111");
smt=con.createStatement();
rs= smt.executeQuery("SELECT * FROM emp");
while(rs.next()){
nameList.add(rs.getString("Name"));
return nameList;
}catch( Exception e){
String msg="Exception:"+e.getMessage();
</code><code class="jive-code jive-java"><font>return nameList;</code><code class="jive-code jive-java">
}finally {
try {
if(con != null)
con.close();
} catch(SQLException e) {}
</code><code>return nameList;</code>
<code class="jive-code jive-java"> } -
To obtain the value of a session variable in a JAVA class
Hello again.
I have a JSP page, in witch I kept a session variable with a value, and later (in the same JSP page) I use a JAVA class to obtain the value stored in this session variable (I make this to verify that this works well and that this is possible)
When I run the file, I obtain the following error:
excepci�n
org.apache.jasper.JasperException
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:372)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:292)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:236)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
causa ra�z
java.lang.NullPointerException
ConfigAnlsEspect.Config.<init>(Config.java:18)
org.apache.jsp.admin.PaleoPlot.configAnEsp_jsp._jspService(configAnEsp_jsp.java:103)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:94)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:324)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:292)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:236)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)And my code is:
------------->The JSP file:<-----------------
session.setAttribute("VarSession", "empty");
<%@ page import="ConfigAnlsEspect.Config"%>
<%
Config ObjConfigAE = new Config();
String valorDev = ObjConfigAE.getValueSession();
out.println("<br>Returned= -->"+valorDev+"<--<br>");
%>
------------->The JAVA class:<-----------------
package ConfigAnlsEspect;
import java.io.*;
import java.net.*;
import java.util.*;
import java.text.*;
import javax.servlet.http.HttpSession;
import javax.servlet.*;
import javax.servlet.http.*;
public class Config extends HttpServlet{
HttpSession session = null;
String valor = null;
public Config (){
valor = (String)session.getAttribute("VarSession");
public String getValueSession(){
return valor;
}Why I obtain java.lang.NullPointerException ??
Thanks very muchI have solved the problem, doing (in the java class):
package ConfigAnlsEspect;
import java.io.*;
import java.net.*;
import java.util.*;
import java.text.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.*;
import javax.servlet.http.*;
public class Config extends HttpServlet{
HttpSession session;
String valor = null;
public Config (HttpSession session){
this.session = session;
valor = (String)this.session.getAttribute("VarSession");
public String getValueSession(){
return valor;
}is it rigth ?? -
How to access variables declared in java class file from jsp
i have a java package which reads values from property file. i have imported the package.classname in jsp file and also i have created an object for the class file like
classname object=new classname();
now iam able to access only the methods defined in the class but not the variables. i have defined connection properties in class file.
in jsp i need to use
statement=con.createstatement(); but it shows variable not declared.
con is declared in java class file.
how to access the variables?
thankshere is the code
* testbean.java
* Created on October 31, 2006, 12:14 PM
package property;
import java.beans.*;
import java.io.Serializable;
public class testbean extends Object implements Serializable {
public String sampleProperty="test2";
public String getSampleProperty() {
return sampleProperty;
}jsp file
<%@ page contentType="text/html;charset=windows-1252"%>
<%@ page import="java.sql.*,java.util.*"%>
<html>
<head>
<title>Schedule Details</title>
</head>
<jsp:useBean id="ConProp" class="property.testbean"/>
<body>
Messge is : <jsp:getProperty name="msg" property="sampleProperty"/>
<%
out.println(ConProp.sampleProperty);
%>
</body>
</html>out.println(ConProp.sampleProperty) prints null value.
is this the right procedure to access bean variables
thanks -
Start JavaFx project using a Java class
After hours of searching, I still can't solve this problem:
I have a pure JavaFx project but need to start it with a Java class.
It used to work with the Interface method, but (I guess) since the javafx update to 1.3, the JavaFx code starts executing (the console outputs FX.println statements) but the stage(s) never become visible.
Activator.java
final Context context = FXLocal.getContext();
final FXClassType instance = context.findClass("javafx.Launcher", this.getClass().getClassLoader());
final ObjectValue obj = (ObjectValue) instance.newInstance();
final LauncherInterface l = (LauncherInterface)obj.asObject();
l.run();LauncherInterface.java
public interface LauncherInterface {
public void run();
}Launcher.fx
public class Launcher extends LauncherInterface {
public override function run() {
// [...] init stuff
MainWindow.createWindow();
}I'm using java version "1.6.0_21", javafx 1.3.0_b412, windows 7
any ideas?
thanks alotThere is someting wrong in my answer that on the FX side you can keep your code but on the java side the call have to be defered to the javaFX container like that:
com.sun.javafx.runtime.Entry.deferAction(
new Runnable() {
@Override
public void run() {
//Create javaFX Stage
);The class is in javafxrt.jar -
Accessing String variables from several JAVA classes
Hi.
I have several java classes that accesses the same String variables. Instead of putting the String declarations in every java files, how can I put these declarations in a single file source, and get each java class to get the variables data from this file ?
Please advice.
Thanks.hi, of course you can solve it by the following methods:
Method 1. define a superclass including the common string variable, and extend other classes from the superclass.
Method 2. define a class , and define your common string variable as a static variable in it. In your other classes, you can call the string variable.
Method 3. define it at your each classes. -
Wrapper classes/ instance variables&methods
can anyone provide me additional information on the wrapper classes.
In addition, could someone please provide an explination of the- instance and class (variables+methods)Every primitive class has a wrapper class e.g.
int - Integer
float - Float
long - Long
char - Character
etc. When a primitive is wrapped it becomes an object and immutable. Primitives are generally wrapped (either to make them immutable) or to be able to add them to the collections framework(sets, maps, lists which can only take objects, not primitives).
An instance variable is a variable that each copy of the object you create contains, as is an instance method. Each instance you create (each copy of the object) contains its own copy of the variable and method.
A class variable and method means that no matter how many objects you create, there will be one and only one copy of the variable and method.
Hope this helps. Also see the java tutorial. -
Save a java class instance in Oracle
Hi,
I would like to save a java object into an oracle table in order to use it later.
Can you tell me if it is possible?
thanks in advance.
Michael.you have to place the java class in BLOB, and read it in and out as a pure binary file....... buth otherwise it should be possible
-
Sub class will allocate seperate memory for super class instance variable?
class A
int i, j;
void showij()
System.out.println("i and j: " + i + " " + j);
class B extends A
int k;
void showij()
System.out.println("i and j: " + i + " " + j);
what is size of class B will it be just 4 byte for k or 12 bytes for i, j and k ?
will be a seperate copy of i and j in B or address is same ?
thank uamit.khosla wrote:
just to add on...if you create seprate objects of A and B, so the addresses will be different. We cant inherit objects, we inherit classes. It means if you have an object of A and another object of B, they are totally different objects in terms of state they are into. They can share same value, but its not compulsary that they will share same values of i &j.
Extending A means to making a new class which already have properties & behaviour of A.
Hope this help.That is very unclear.
If you create two objects, there will be two "addresses", and two sets of member variables.
If you create one object, there will be one "address", and one complete set of non-static member variables that is the union of all non-static member variables declared in the class and all its ancestor classes. -
How to log the error/variables info in java classes
We are using the third party jar and the jar is independent to the application. So this is why I am not able to see any errors in the web server log. In that file using the below sample code is using. And my problem is I am not able to print the variables info either in web page or in the terminal. Please can any one suggest how to make it possible(to print the variables info).Just fyi, the methods in this class are calling by Java bean and the java bean in turn calling by servlet.
============================
import SPSecurity.configuration.SecurityConfiguration;
import SPSecurity.exception.NoDataFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
import javax.servlet.http.*;
public class BasicUserInformation
public BasicUserInformation()
//intialization
public void initialize(String s, int i)
//some code with variables
public void initialize(HttpServletRequest httpservletrequest)
// some code with variables
private void setUserIdandTypeProperties()
//Some code with variable.
}The answer is reflection
Read the following tutorial
[http://java.sun.com/docs/books/tutorial/reflect/index.html] -
Java Class Instance Referencing Question...
Perhaps i worded that title poorly, but this is what I am talking about...
This is an example, much simpler than what i am working on.
class Alive(){
public boolean alive;
public Alive(){
alive = true;
public kill(){
alive = false;Now let us say that I want two things to reference this...let us just assume that class person has an instance of class Alive in it called living;
Person x, y;
x.living = new Alive();
y.living = x.living;
y.living.kill();is x dead? in other words, did changing the status if y.living after saying it was equal to x.living alter x.living? If not, is it possible to do this?You only have one instance of Alive, but multiple References. By calling the kill method you are killing the alive on both x and y. Because it is the same Alive object.
-
Is there any configuration file that binds the jsp page and the java class? I need to replace some jsp pages and their classes in different packages, but the pages cannot find their classes. Does anybody know where/how I can set the appropriate binding?
Thanks,
Kelly.It's not configurable (yet). The page name, and the "backing bean", must have the same name (including case), and the java class needs to be in the package folder with the rest of the backing beans.
-- Tor
http://blogs.sun.com/tor -
Passing numerical variables to and from a Java class
I'm trying to do something that seems like it should be fairly simple, but apparently it isn't. I'm new to Java and JDBC, so I'm hoping that I'm missing something fundamental and fairly basic.
Basically, I want to pass a set of (number) variables to a Java class from a PL/SQL Procedure, and get back a series of numbers based on calculations to the first set of numbers. (In my real world project, I have to perform a series of matrix calculations to determine regression parameters for two sets of data, but we'll keep this simple.) However, I can find nothing that tells me how to do this, and I'm receiving a series of errors when I attempt it.
For example, let's say I want to send in two decimal numbers, a and b, and receive back the sum s, the difference d, the product p and the quotient q. So, the java class would be:
* MathEx.java
class MathEx {
public static void main(double a, double b, double sum, double diff, double prod, double quo) {
sum = a + b;
diff = a - b;
prod = a * b;
quo = a / b;
Fairly simple, right? It compiles fine using "javac MathEx.java", and then I load the class into the database:
loadjava -u steve/steve MathEx.class
Everything works great. Now, I create a wrapper Procedure. This is where the problem comes in. How do I declare the incoming and outgoing parameters in the Procedure? No matter what I try, I get " the declaration of "MathEx.main([whatever])" is incomplete or malformed"
The procedure I'm trying is:
create or replace procedure Call_MathEx
a NUMBER,
b NUMBER,
s NUMBER,
d NUMBER,
p NUMBER,
q NUMBER
AS
language JAVA
name 'MathEx.main(oracle.sql.NUMBER,oracle.sql.NUMBER,
oracle.sql.NUMBER,oracle.sql.NUMBER,oracle.sql.NUMBER,oracle.sql.NUMBER,)';
I've tried the following values for possible variable types in the "name 'MathEx.main(" statement:
oracle.sql.NUMBER
java.lang.Number
java.lang.Double
java.Math.BigDecimal
The only thing I can get to work is if I just use "java.lang.string[]" and send everything at once, then use parseDouble() to read the parameters inside the Java class. However, that makes it impossible to then read the new values of the sum, difference, product and quotient in the calling procedure, since the variable retain the same value as before the call to the Java class.
Any help is greatly appreciated.Java Stored Procedures Developers Guide (part of the docs and here on OTN) would probably help.
I suspect you need:
create or replace procedure Call_MathEx
a IN NUMBER,
b IN NUMBER,
s OUT NUMBER,
d OUT NUMBER,
p OUT NUMBER,
q OUT NUMBER
AS
language JAVA
name 'MathEx.main(oracle.sql.NUMBER,oracle.sql.NUMBER,
oracle.sql.NUMBER,oracle.sql.NUMBER,oracle.sql.NUMBER,oracle.sql.NUMBER,)';
Not sure, I always let JDeveloper handle it for me :) -
Java class how to load a JavaFX class?
I want to start a JavaFX application from a Java class,how can implement it?
Thank you so much!I want to start a JavaFX application from a Java class,how can implement it?
Thank you so much!
Maybe you are looking for
-
Error while updating the Patch
Hi, I defined import queue to import the patches for SAP_BASIS, but while importing the patches it gives error "Current program has been modified while running", & screen become blank, I try so many times to continue & after that I click from menu er
-
A JRE or JDK must be available in order to run Eclipse
Hello Colleagues , I have started with the SAP HANA Basics course offered at OpenSAP . I am at my first steps for Installing Eclipse . Please refer to the following link :- http://hcp.sap.com/developers/learningtutorial111.html After Downloading Ecli
-
Re: Satelite L850-13R - HDMI is not working
I have been using my HDMI cable to connect Laptop and TV very rare. It was just fine. Yesterday I used it and it worked, then I have turned it again today and it is not working anymore. What could I do to make it working again?
-
Direct printing with BI delivery
Hi all, I've got a problem when sending reports to a printer automatically after the launching the job, with JDEdwards. The RD output that I get is correct, but when I go and check the document that just came out of the printer, it doesn't contain an
-
Hello, I created an employees table with 3 types, although when I insert the values, it works but doesn't display the last value which is from a different type. Any idea how to fix this? DROP TYPE employees_type FORCE; DROP TYPE hourly_employees FORC