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

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+"'";

Related

Client java code fails running when server Tom Cat is not running in REST or check if server is on from client in REST

I am new to web services. I am using Rest
Trying to connect the url
http://localhost:8080/CrunchifyRESTJerseyExample/crunchify/ctofservice/22
from a client java program
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
public class CrunchifyRESTJerseyNetURLClient {
public static void main(String[] args) {
System.out.println("\n============Output:============ \n"
+ callURL("http://localhost:8080/CrunchifyRESTJerseyExample/crunchify/ctofservice/22"));
}
public static String callURL(String myURL) {
System.out.println("Requested URL: " + myURL);
StringBuilder sb = new StringBuilder();
URLConnection urlConn = null;
InputStreamReader in = null;
try {
URL url = new URL(myURL);
urlConn = url.openConnection();
if (urlConn != null)
urlConn.setReadTimeout(60 * 1000);
if (urlConn != null && urlConn.getInputStream() != null) {//checked hear
in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset());
BufferedReader bufferedReader = new BufferedReader(in);
if (bufferedReader != null) {
int cp;
while ((cp = bufferedReader.read()) != -1) {
sb.append((char) cp);
}
bufferedReader.close();
}
}
in.close();
} catch (Exception e) {
throw new RuntimeException("Exception while calling URL:" + myURL, e);
}
return sb.toString();
}
}
The code runs fine on active server ie when tomcat is running.
But problem is when the server is not running.
It is throwing an exception like:
Requested URL: http://localhost:8080/CrunchifyRESTJerseyExample/crunchify/ctofservice/22
Exception in thread "main" java.lang.RuntimeException: Exception while calling URL:http://localhost:8080/CrunchifyRESTJerseyExample/crunchify/ctofservice/22
at com.crunchify.client.CrunchifyRESTJerseyNetURLClient.callURL(CrunchifyRESTJerseyNetURLClient.java:40)
at com.crunchify.client.CrunchifyRESTJerseyNetURLClient.main(CrunchifyRESTJerseyNetURLClient.java:14)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(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.plainConnect0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at com.crunchify.client.CrunchifyRESTJerseyNetURLClient.callURL(CrunchifyRESTJerseyNetURLClient.java:27)
... 1 more
I have checked
if (urlConn != null)
if (urlConn != null && urlConn.getInputStream() != null)
But still the code gets executed throwing exception
Kindly help
what needs to be handled .
You can access a web URL only if the server on which it is deployed is in running state. It is true for all the web pages and APIs that exists.
If you want to display some meaningful message or do some other work in case the API is not reachable, then don't throw the error (You are throwing throw new RuntimeException("Exception while calling URL:" + myURL, e); in the catch block.) or catch the thrown error in the calling method ie in main method. In the catch block you can just print some message on console or call alternate API that displays user friendly message.

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.

Java SQL Exception when creating a DSNless connection

Here is my code:
package dsnless;
import java.sql.*;
////////////////////////////////////////////////////////////
//This class will be used to fire queries to the database
////////////////////////////////////////////////////////////
public class Query {
public Query(){
String pathToDatabase = "E:/Eclipse Projects/JDBC/src/datasouce/School.mdb";
String database = "jdbc:odbc:Driver="+
"{Microsoft Access Driver(*.mdb,*.accdb)};" +
":DBQ=" + pathToDatabase;
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection(database);
}catch(Exception e){
e.printStackTrace();
}
}
public static void main(String[] args) {
new Query();
}
Connection con;
Statement s;
ResultSet r;
}//class Query end
Here is the exception:
java.sql.SQLException: [Microsoft][ODBC Driver Manager] DRIVER keyword syntax error
at sun.jdbc.odbc.JdbcOdbc.createSQLException(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.standardError(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.SQLDriverConnect(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcConnection.initialize(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcDriver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at dsnless.Query.<init>(Query.java:14)
at dsnless.Query.main(Query.java:20)
And there is a new exception, too:
[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified
at sun.jdbc.odbc.JdbcOdbc.createSQLException(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.standardError(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.SQLDriverConnect(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcConnection.initialize(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcDriver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at dsnless.Query.<init>(Query.java:14)
at dsnless.Query.main(Query.java:20)
Question
Please tell me what is wrong. I suspect it is the String database but stil it is only a guess.
Nailed it, myself
I changed the extensions supported from (*.mdb,*.accdb) to only (*.mdb) and it worked. Any idea as to why that happened???
You have an additional colon here, remove it
String database = "jdbc:odbc:Driver="+
"{Microsoft Access Driver(*.mdb,*.accdb)};" +
":DBQ=" + pathToDatabase;
^

Apache Derby: SQLSyntaxErrorException

Please have a look at the following code
package normal;
//This class if s for checking the database. If the database doesn't exists, this class will create one
import java.sql.*;
public class DatabaseCheck
{
private Connection con;
public DatabaseCheck()
{
createConnection();
try
{
Statement st = con.createStatement();
st.executeQuery("select * from PhoneData");
}
catch(Exception e)
{
System.out.println(e.getLocalizedMessage());
if(e.getLocalizedMessage().equals("Schema 'SA' does not exist"))
{
try
{
PreparedStatement ps = con.prepareStatement("create table PhoneData(ids int identity constraint pkId primary key,names varchar(20),mobileNumber1 varchar(20),mobileNumber2 varchar(20),landNumber1 varchar(20),landNumber2 varchar(20),address varchar(100),category varchar(20),nickName varchar(20),email varchar(20),middleName varchar(20),lastName varchar(20),city varchar(20),country varchar(20))");
ps.execute();
PreparedStatement ps2 = con.prepareStatement("create table Emails(accountType varchar(10) constraint pk_user primary key,userName varchar(50) ,passwords varchar(50))");
ps2.execute();
}
catch(Exception e2)
{
e2.printStackTrace();
}
}
}
finally
{
closeConnection();
}
}
public void createConnection()
{
try
{
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
con = DriverManager.getConnection("jdbc:derby:PhoneBook;create=true","sa","sasasa");
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void closeConnection()
{
try
{
con.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
This class is capable of programmatically creating tables in embedded apache derby database. But, it gives the following error
java.sql.SQLSyntaxErrorException: Syntax error: Encountered "identity" at line 1, column 32.
at org.apache.derby.impl.jdbc.SQLExceptionFactory40.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.TransactionResourceImpl.wrapInSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.TransactionResourceImpl.handleException(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.handleException(Unknown Source)
at org.apache.derby.impl.jdbc.ConnectionChild.handleException(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedPreparedStatement.<init>(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedPreparedStatement20.<init>(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedPreparedStatement30.<init>(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedPreparedStatement40.<init>(Unknown Source)
at org.apache.derby.jdbc.Driver40.newEmbedPreparedStatement(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.prepareStatement(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.prepareStatement(Unknown Source)
at normal.DatabaseCheck.<init>(DatabaseCheck.java:27)
at normal.MyPhoneBookApp.main(MyPhoneBookApp.java:25)
Caused by: java.sql.SQLException: Syntax error: Encountered "identity" at line 1, column 32.
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.SQLExceptionFactory40.wrapArgsForTransportAcrossDRDA(Unknown Source)
... 15 more
Caused by: ERROR 42X01: Syntax error: Encountered "identity" at line 1, column 32.
at org.apache.derby.iapi.error.StandardException.newException(Unknown Source)
at org.apache.derby.impl.sql.compile.ParserImpl.parseStatement(Unknown Source)
at org.apache.derby.impl.sql.GenericStatement.prepMinion(Unknown Source)
at org.apache.derby.impl.sql.GenericStatement.prepare(Unknown Source)
at org.apache.derby.impl.sql.conn.GenericLanguageConnectionContext.prepareInternalStatement(Unknown Source)
... 9 more
When I remove the "identity" keyword from the table creation code, this work fine. But, auto generation of ID's is mandatory. Please help!
Derby has no identity column type (as documented in the manual). You need to define a generated column. For the generation definition, Derby indeed knows an identity attribute, but that's not a datatype.
So the column definition for ids should be
ids integer generated always as identity constraint pkId primary key
Note that you can also use generated by default instead of always. Then a value will only be generated if you don't specify a value for that column during insert. generated always will overwrite any value you provide.
The Apache Derby documentation indicates you can replace the identity keyword with:
NOT NULL GENERATED ALWAYS AS IDENTITY

Timer in java using Eclipse

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();

Categories