Timer in java using Eclipse - java

I'm trying to do a little program in Java using Eclipse, and I'm a little bit lost.
Could anybody explain me (in a "for dummies way") what do I have to do for repaint a form using a timer?
I'm trying to do something as simple as a clock. I need a timer to repaint it every second.
Something like this:
private void activateTimer()
{
ActionListener myAction;
myAction = new ActionListener ()
{
public void actionPerformed(ActionEvent e)
{
whatever.redraw();
}
};
myTimer = new Timer(1000, myAction);
myTimer.start();
}
When the action must be performed, I receive the error:
*Exception in thread "AWT-EventQueue-0" org.eclipse.swt.SWTException: Invalid thread access*
This is the full exception I receive:
Exception in thread "AWT-EventQueue-0" org.eclipse.swt.SWTException: Invalid thread access
at org.eclipse.swt.SWT.error(SWT.java:4282)
at org.eclipse.swt.SWT.error(SWT.java:4197)
at org.eclipse.swt.SWT.error(SWT.java:4168)
at org.eclipse.swt.widgets.Widget.error(Widget.java:468)
at org.eclipse.swt.widgets.Widget.checkWidget(Widget.java:359)
at org.eclipse.swt.widgets.Control.redraw(Control.java:2327)
at default.myTimer$1.actionPerformed(myTimer.java:97)
at javax.swing.Timer.fireActionPerformed(Unknown Source)
at javax.swing.Timer$DoPostEvent.run(Unknown Source)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$000(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Any idea or any sample about refreshing a screen every second?
I've followed the instructions in one of the answers but I'm still receiving the same error.

you have to split that to the separete methods, better would be using javax.swing.Action instead of ActionListener
private void activateTimer(){
myTimer = new Timer(1000, myAction);
myTimer.start();
}
private Action myAction = new AbstractAction() {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
whatever.redraw();
}
};

Why not use the timer functionality that is built into the SWT Display class?
private void activateTimer(final Display display)
{
display.timerExec(
1000,
new Runnable() {
public void run() {
whatever.redraw();
// If you want it to repeat:
display.timerExec(1000, this);
}
});
}

This page may be useful.
If you use SWT, do it in SWT way :)
EDIT:
The problem is widget should be updated by eclipse's thread. Try this code.
Job job = new Job("My Job") {
#Override
protected IStatus run(IProgressMonitor monitor) {
Display.getDefault().asyncExec(new Runnable() {
#Override
public void run() {
while(true)
{
Thread.sleep(1000);
whatever.redraw();
}
}
});
return Status.OK_STATUS;
}
};
job.schedule();

Related

RMI Server-side java.net.MalformedURLException: unknown protocol: c

I surfed the net for 2 days, and I didn't find a solution formyproblem, so I decided to ask here.
I'm doing a book exercise: "Write a program Client-Server with Java RMI, that return the sum of integer given by clients. It has to implement a method to add an integer, anda method to get the total".
I'm facing with the Server-side.
The error the program returns is:
java.rmi.UnmarshalException: Error unmarshaling return; nested exception is:
java.net.MalformedURLException: unknown protocol: c
at sun.rmi.transport.StreamRemoteCall.executeCall(Unknown Source)
at sun.rmi.server.UnicastRef.invoke(Unknown Source)
at sun.rmi.registry.RegistryImpl_Stub.bind(Unknown Source)
at java.rmi.Naming.bind(Unknown Source)
at ContatoreServer.main(ContatoreServer.java:15)
Caused by: java.net.MalformedURLException: unknown protocol: c
at java.net.URL.<init>(Unknown Source)
at java.net.URL.<init>(Unknown Source)
at java.net.URL.<init>(Unknown Source)
at sun.rmi.server.LoaderHandler.pathToURLs(Unknown Source)
at sun.rmi.server.LoaderHandler.getDefaultCodebaseURLs(Unknown Source)
at sun.rmi.server.LoaderHandler.loadClass(Unknown Source)
at java.rmi.server.RMIClassLoader$2.loadClass(Unknown Source)
at java.rmi.server.RMIClassLoader.loadClass(Unknown Source)
at sun.rmi.server.MarshalInputStream.resolveClass(Unknown Source)
at java.io.ObjectInputStream.readNonProxyDesc(Unknown Source)
at java.io.ObjectInputStream.readClassDesc(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
... 5 more
Here there are my classes:
LocalObject
public class ContatoreLocale {
private int num;
public ContatoreLocale(){
this.num=0;
}
public synchronized int get(){
return this.num;
}
public synchronized void add(int i){
this.num+=i;
}
}
Remote Interface
public interface IContatore extends Remote{
int get() throws RemoteException;
void add(int i) throws RemoteException;
}
Remote Object
public class ContatoreRemoto extends ContatoreLocale implements IContatore{
Logger log= Logger.getLogger("global");
//Costruttore
public ContatoreRemoto() throws RemoteException{
super();
UnicastRemoteObject.exportObject(this, 0);
try {
Naming.rebind("Contatore", this);
//errore
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
public int get(String nome) throws RemoteException{
return this.get();
}
public void add(String nome,int i) throws RemoteException{
this.add(i);
}
}
Server
public class ContatoreServer {
static Logger log= Logger.getLogger("global");
public static void main(String[] args) {
try {
ContatoreRemoto cr=new ContatoreRemoto();
log.info("Server Pronto");
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
Please, help me :S
In my experience, this has to do with the absolute path in the File System where the RMI Eclipse project is placed. I think you may have a blank, a space, in the path. So RMI is unable to parse the path and it is interrupted, ... then we get the 'malformed' exception. It might be near a 'c', and for this reason, you get the 'c' in the exception.
I recommend you go to the file system, navigate to the project folder, and check the absolute path to the project. I bet you have a blank.
Such as c:\Users\mylab c\MyProjects....
Did you notice the blank space?

Updating a java.sql.Date into a database using PreparedStatement

I've been scratching my head for the past few hours wondering what is wrong. I want to edit a Date/Time format on my access database and it'a just keeps on confusing me as to why I cant update it. This is my code and I will explain. . .
This is the Main class where there's a button that says update and when clicked will lead to another class called UpdateBooking_Run()
public MainInterface() {
JButton updateBookings = new JButton("UPDATE");
updateBookings.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
UpdateBooking_Run ub = new UpdateBooking_Run();
ub.setVisible(true);
}
});
}
This is UpdateBooking_Run() without the textboxes only the button inside this class...As you can see from string, I converted the date to java.sql.Date
public class UpdateBooking_Run extends JFrame {
public static java.sql.Date sqldate;
public UpdateBooking_Run() {
JButton btnAdd = new JButton("UPDATE");
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
Integer.parseInt(yearBookings.getText().trim());
}
catch (NumberFormatException na) {
JOptionPane.showMessageDialog(null, "Please input year", "Error", JOptionPane.ERROR_MESSAGE);
}
DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
String mu = monthBookings.getSelectedItem().toString();
String da = dayBookings.getSelectedItem().toString();
String ye = yearBookings.getText().trim();
String dat = ye + "/" + mu + "/" + da ;
java.util.Date date = null;
try {
date = df.parse(dat);
} catch (ParseException e) {
e.printStackTrace();
}
sqldate = new java.sql.Date(date.getTime());
try {
UpdateConn_Run uc = new UpdateConn_Run();
uc.updateDate();
}
catch (Exception en) {
en.printStackTrace();
}
}
});
}
}
As you can see in the code above, I set sqldate as static mainly because it worked with updating string on my other classes but I just cant seem to update Date. . .
Then this is the connection... Or UpdateConn_Run()
public class UpdateConn_Run {
Connection con;
Statement st;
ResultSet rs;
StringBuffer results;
String url = "jdbc:ucanaccess://C://DATABASE//DATA.accdb";
PreparedStatement ps;
public void updateBooking() {
try {
int i = 1;
UpdateBooking_Run ubr = new UpdateBooking_Run();
MainInterface mi = new MainInterface();
Date da = UpdateBooking_Run.sqldate;
con = DriverManager.getConnection(url);
//theres actually an uneditable textbox in MainInterface that shows the ID of the selected row
int id = Integer.parseInt(mi.idstringBookings);
String sql = "UPDATE bookings SET date ='"+da+"' WHERE ID ='"+id+"'";
ps = con.prepareStatement(sql);
ps.executeUpdate();
ps.close();
con.close();
if (i == 1) {
JOptionPane.showMessageDialog(null, "Database has been updated please click Refresh");
}
}
catch (Exception e) {
e.printStackTrace();
}
}
I also seem to get the error...
net.ucanaccess.jdbc.UcanaccessSQLException: data exception: invalid datetime format
at net.ucanaccess.jdbc.UcanaccessPreparedStatement.executeUpdate(UcanaccessPreparedStatement.java:261)
at interfaceSystem.UpdateConn_Run.updateBooking(UpdateConn_Run.java:109)
at interfaceSystem.UpdateBooking_Run$2.actionPerformed(UpdateBooking_Run.java:284)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
But it still confuses me . . .
It says invalid datetime format so I went ahead and changed the format again and again. Even tried the format in MS Access the problem still persists.
Tried not putting in the date as static. I just get "null".
Can someone explain why static is used for updating databases in PreparedStatements? Still confuses me to this day... (Everyone in my class seems to be using it although I have no idea why)
I am sorry for my English. I am not a native speaker so I appreciate it if you have questions regarding grammar...
Since you're using a PreparedStatement, you should be using placeholders and your code should be as follow:
query = "UPDATE bookings SET date = ? WHERE id = ?";
preparedStatement = con.prepareStatement(query);
preparedStatement.setDate(1, da);
preparedStatement.setInt(2, id);
preparedStatement.executeUpdate();
Because you're including a Date object into a String, it will be parsed using its toString() method, and your statement will look like:
"UPDATE bookings SET date = 2000-01-12 WHERE id = 22"
I don't do Java, but your final SQL for Access must look like this:
"UPDATE bookings SET date = #2017/03/21# WHERE ID = '1'";
or, if ID is numeric:
"UPDATE bookings SET date = #2017/03/21# WHERE ID = 1";
Thus, something like:
//datestring = da formatted as "2017/03/20"
String sql = "UPDATE bookings SET date =#"+datestring+"# WHERE ID ='"+id+"'";

java.lang.IllegalStateException: Not on FX application thread; currentThread = Thread-4

I'm trying to set the string of a Text object from a Thread but it's giving me this error:
Exception in thread "Thread-4" java.lang.IllegalStateException: Not on FX application thread; currentThread = Thread-4
at com.sun.javafx.tk.Toolkit.checkFxUserThread(Unknown Source)
at com.sun.javafx.tk.quantum.QuantumToolkit.checkFxUserThread(Unknown Source)
at javafx.scene.Scene.addToDirtyList(Unknown Source)
at javafx.scene.Node.addToSceneDirtyList(Unknown Source)
at javafx.scene.Node.impl_markDirty(Unknown Source)
at javafx.scene.shape.Shape.impl_markDirty(Unknown Source)
at javafx.scene.Node.impl_geomChanged(Unknown Source)
at javafx.scene.text.Text.impl_geomChanged(Unknown Source)
at javafx.scene.text.Text.needsTextLayout(Unknown Source)
at javafx.scene.text.Text.needsFullTextLayout(Unknown Source)
at javafx.scene.text.Text.access$200(Unknown Source)
at javafx.scene.text.Text$2.invalidated(Unknown Source)
at javafx.beans.property.StringPropertyBase.markInvalid(Unknown Source)
at javafx.beans.property.StringPropertyBase.set(Unknown Source)
at javafx.beans.property.StringPropertyBase.set(Unknown Source)
at javafx.scene.text.Text.setText(Unknown Source)
at uy.com.vincent.fx.handling.TableController$1.run(TableController.java:70)
Handler Class:
#FXML
private Text timer;
#Override
public void initialize(URL url, ResourceBundle rb) {
init();
new Thread() {
public void run() {
while(true) {
Calendar cal = new GregorianCalendar();
int hour = cal.get(cal.HOUR);
int minute = cal.get(cal.MINUTE);
int second = cal.get(cal.SECOND);
int AM_PM = cal.get(cal.AM_PM);
String time = hour + "" + minute + "" + second;
timer.setText(time);
}
}
}.start();
}
I'm following a tutorial.
The guy in the tutorial is not using JavaFX.
I have tried using Platform.runLater(), it does work but it crashes my program.
I also tried creating a Timer on the Platform.runLater(new Runnable() { }) method but it gives me the same error as before.
Wrap timer.setText() in Platform.runLater(). Outside it, inside the while loop, add Thread.sleep(1000);
The reason behind Illegal State Exception is you are trying to update UI on some thread other than JavaFX Application thread.
The reason why your app was crashing when you added it was you were overloading the UI thread by adding a process to be executed on the UI thread infinitely. Making the thread sleep for 1000ms will help you overcome the issue.
If possible replace while(true) with a Timer or TimerTask.
For more options follow this link

Getting strange http time out error in threads

I'm using the ARIN rest whois service to look up the organizations for a list of IP addresses. Since the list is very long (the one below is just a very small subset), I opted to do this with threads for faster performance.
public class SimpleThreadPool {
public final static String[] ips = {
"192.150.16.64","192.243.232.36","208.77.139.8","63.140.35.160",
"63.140.35.161","63.140.35.162","63.140.59.142","63.140.61.200",
"66.235.132.238","66.235.137.133","66.235.138.18","66.235.138.192",
"66.235.138.195","66.235.139.152","66.235.139.172","66.235.139.204",
"66.235.139.205","66.235.139.206","66.235.139.227","66.235.141.144",
"66.235.141.145","66.235.141.146","66.235.141.16","66.235.142.20",
"66.235.142.24","66.235.141.145","184.106.60.35","207.171.162.26",
"207.171.162.75","207.171.162.95","207.171.185.201","207.171.187.117",
"207.171.187.118","207.171.189.80","207.171.189.81","216.137.37.108",
"216.137.37.122","216.137.37.128","216.137.37.138","216.137.37.140",
"216.137.37.178","216.137.37.183","216.137.37.198","216.137.37.225",
"216.137.37.235","216.137.37.37","216.137.37.52","216.137.37.57",
"216.137.37.6","216.137.37.84"
};
public static void main(String[] args) throws InterruptedException {
ExecutorService executor = Executors.newFixedThreadPool(4);
for (int i = 0; i < ips.length; i++) {
Runnable worker = new WorkerThread(ips[i]);
executor.execute(worker);
}
executor.shutdown();
while (!executor.isTerminated()) {}
System.out.println("All threads finished.");
}
}
And here is WorkerThread:
public class WorkerThread implements Runnable {
private String workingIP;
public WorkerThread(String workingIP) {
this.workingIP = workingIP;
}
#Override
public void run() {
try {
URL url = new URL("http://whois.arin.net/rest/ip/" + workingIP);
InputStream inputStream = null;
HttpURLConnection con = (HttpURLConnection)(url.openConnection());
con.connect();
inputStream = con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
String line = null;
while( (line=br.readLine()) != null )
{
if (line.contains("<td>Organization</td><td>")) {
String companyName = line.replace("<td>Organization</td><td>", "").trim();
System.out.println(workingIP + " maps to: " + companyName);
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
On my work machine (w/ an i5-2400, 4GB RAM, 32bit Win7), this code works fine all the way down to around the 45th+ IP address in the array. Then I get java.net.ConnectException errors thrown for the remaining lookups:
...
216.137.37.57 maps to: Amazon.com, Inc.
216.137.37.6 maps to: Amazon.com, Inc.
java.net.ConnectException: Connection timed out: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.<init>(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source)
If I change the executor's thread pool size to 1, then everything works and no errors are thrown, but obviously the lookups take a lot longer.
The really strange thing is that if I run this same code on my 2011 Core i7 Mac, no errors whatsoever are thrown. Granted, the two are on different networks (my work machine uses my work's network, while my Mac is wirelessly tethered to a smartphone).
Any idea what's going on here, and what I can do to fix it?
You need to write sane error-handling code. It really is that simple. What do you want to do if the connection times out? If you make a lot of connections at once on a slow network, some of them may time out.

Why am I getting a nullPointerException when Clojure code calls a JPanel function?

I am having trouble determining why my code gets a nullPointer exception. I'm trying to write a swing application using a combination of Java and Clojure. I have a Clojure function that calls a function in my JPanel subclass, and I'm getting a lot of exceptions that are driving me crazy.
I've simplified my code as much as possible, and I'm still getting these errors.
(defn draw-state
"Draws the current state."
[state display]
(do-swing (.drawBlocks display)))
Here's the entire JPanel subclass, although I think the only relevant part is the drawBlocks function (which eventually will be replacing the blocks array):
public class TDisplay extends JPanel {
private Block[] blocks = new Block[1];
/**
* Create the panel.
*/
public TDisplay() {
setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
setBackground(Color.WHITE);
setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
blocks[0] = new Block(3, 4, 0);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
for (Block b : blocks) {
if (b == null) continue;
switch (b.colour) {
case 0:
g.setColor(Color.WHITE);
break;
case 1:
g.setColor(Color.BLACK);
break;
}
g.fillRect(b.x * Block.SIZE, b.y * Block.SIZE, Block.SIZE, Block.SIZE);
}
}
public void drawBlocks() {
System.out.println("Hello world");
}
}
And the stack trace:
Exception in thread "AWT-EventQueue-0" java.lang.RuntimeException: java.lang.NullPointerException
at clojure.lang.AFn.run(AFn.java:28)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Caused by: java.lang.NullPointerException
at clojure.lang.Reflector.invokeNoArgInstanceMember(Reflector.java:263)
at core$draw_state$fn__401.invoke(core.clj:43)
at clojure.lang.AFn.run(AFn.java:24)
... 8 more
I have the feeling that I'm missing something really obvious, and I'd appreciate any help.
Thanks!
How about the code that invokes draw-state -- is it possible that's passing in nulls for display?

Categories