Time Difference between events - java

I am trying to calculate the time difference between the user-set-date and the current-system-date.
My code is as follows,
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JFrame;
public class Main {
public static void main(String[] args){
// Make the frame
JFrame appFrame = new JFrame("Get Things Done");
// Make a panel
WelcomePanel buttonPanel = new WelcomePanel();
// Set the class button to work
appFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Add the panel to the frame
appFrame.add(buttonPanel);
// Set the size of the frame
appFrame.setSize(400, 400);
// Make the frame visible
appFrame.setVisible(true);
appFrame.pack();
WelcomePanel welcome = new WelcomePanel();
// --------------------------------------------------------------------------
// Print currentTime
Time time = new Time();
time.printCurrentTime();
UserEvent input = new UserEvent();
// Test inputTime
input.setInputTime("15/05/28 18:00:00");
System.out.println("***Test Getters and Setters***");
System.out.println(input.getInputTime());
} // end main
} // end class
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Time {
Date currentDate = new Date();
UserEvent user = new UserEvent();
// Print current time
public void printCurrentTime(){
DateFormat dateFormat = new SimpleDateFormat ("yy/MM/dd HH:mm:ss");
// System.out.println("date without format: "+ currentDate.toString());
System.out.println(dateFormat.format(currentDate));
} // end printCurrentTime
public long getCurrentTime(){
return currentDate.getTime();
}
// ----------------------------------------------------------------------------
} // end class
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class UserEvent {
private String inputTime;
Date user = new Date();
// set inputTime
public void setInputTime(String newInputTime){
inputTime = newInputTime;
} // end setInputTime
// get inputTime
public String getInputTime(){
return inputTime;
} // end getInputTime
public void parseInput(){
DateFormat dateFormat = new SimpleDateFormat ("yy/MM/dd HH:mm:ss");
try{
user = dateFormat.parse(inputTime);
System.out.println(user);
} catch (ParseException error){
System.out.println("Are you sure you entered a date?");
} // end try/catch
}
// ---------------------------------------------------------------------------
}
I have been searching for lots and lots of examples, but still no progress on my code.

public static void main(String[] argv) throws InterruptedException // Thread.sleep throws that
{
Random rng = new Random();
Date start = new Date();
Thread.sleep(rng.nextInt(1000)); // sleep for 0-999 ms
Date end = new Date();
System.out.println("Slept for " + (end.getTime() - start.getTime()) + "ms.");
}
Possible output is: Slept for 590ms.
You can try it yourself here.

Related

Using Timer.schedule to make java program run at a specific time Not working

I am trying to get use Timer.schedule() to make a task run automatically at a certain time. However, it is not working.
my code:
I tried to set up a timer task first
I then tried to create a Date object using the current time
I then use Timer.schedule(timertask, date) to tell the computer when to do the task.
However, the timertask doesn't start at the specified date.
Please help, thank you.
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class Main {
public static void main(String[] args){
Timer timer = new Timer();
TimerTask task = new TimerTask() {
#Override
public void run() {
System.out.println("Starts");
BookingPage page = new BookingPage();
page.logIn();
page.selectCourseAndTime();
page.finishSelectTime();
}
};
Date date = generateDate();
timer.schedule(task, date);
}
public static Date generateDate() {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd");
LocalDateTime now = LocalDateTime.now();
String[] arr = dtf.format(now).split("/");
int[] currentTime = new int[arr.length];
for (int i = 0; i < currentTime.length; i++) {
currentTime[i] = Integer.parseInt(arr[i]);
}
Calendar calendar = Calendar.getInstance();
calendar.set(currentTime[0], currentTime[1], currentTime[2], 15, 24, 0);
Date date = calendar.getTime();
return date;
}
}
I think this solves the problem
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class MyTimerTask extends TimerTask {
#Override
public void run() {
System.out.println("Timer task started at:"+new Date());
completeTask();
System.out.println("Timer task finished at:"+new Date());
}
private void completeTask() {
try {
//assuming it takes 20 secs to complete the task
Thread.sleep(20000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String args[]){
TimerTask timerTask = new MyTimerTask();
//running timer task as daemon thread
Timer timer = new Timer(true);
timer.scheduleAtFixedRate(timerTask, 0, 10*1000);
System.out.println("TimerTask started");
//cancel after sometime
try {
Thread.sleep(120000);
} catch (InterruptedException e) {
e.printStackTrace();
}
timer.cancel();
System.out.println("TimerTask cancelled");
try {
Thread.sleep(30000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
When doing calendar.set(year, month, day, hour, minute, second)
month needs to be one less than the current month. For example, May is 4.
problem solved!

Java Timer Countdown from certain time

using Java and Java Swing for a GUI. The scenario is that I want a user to enter in a desired time (in a JTextbox) in the format of HH:MM:SS and from that given time, countdown by seconds until it hits zero.
Currently I am using a timer and the timer.between function. I create an Instant() from the user input time and also use instant.now().
The instants are being created, however, the countdown clock doesn't count down from the user input time, but rather some random numbers that I can't figure out where they are coming from. Can anyone else see the problem?
javax.swing.Timer countDown = new javax.swing.Timer(1000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Duration countingDown = Duration.between(Instant.now(), userInputCountDown);
autoShutOffTF.setText(String.format("%02d:%02d:%02d",
countingDown.toHours(),
countingDown.toMinutes() % 60,
countingDown.getSeconds() % 60));
}
});
startButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//Getting user input, parsing String in the form of HH:MM:SS
String countdownInput = autoShutOffTF.getText();
String getHours = countdownInput.substring(0,2);
int hours = Integer.parseInt(getHours);
String getMins = countdownInput.substring(3,5);
int mins = Integer.parseInt(getMins);
String getSecs = countdownInput.substring(6,8);
int seconds = Integer.parseInt(getSecs);
//Creating a date instance, to get the current year, month and date
Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
//creating a new calendar with all of the data
Calendar cal = Calendar.getInstance();
cal.set(year, month, day, hours, mins, seconds);
//creating a new instant with the new calendar with all of the data
userInputCountDown = cal.toInstant();
//starting timer
countDown.start();
}
});
Don't use Date or Calendar, the java.time API is more the capable of achieving what you want.
Looking at this...
Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
//creating a new calendar with all of the data
Calendar cal = Calendar.getInstance();
cal.set(year, month, day, hours, mins, seconds);
You're creating a new time, based on the hours/mins/seconds, but, what worries me is, is what happens if the time is less than now? This "might" be the issue you're having.
So, some thing you might want to do is verify if the time is before or after the current time and roll the day accordingly - assuming you want to use an absolute time (ie create a timer which counts down from now to 6pm)
This...
Duration countingDown = Duration.between(Instant.now(), userInputCountDown);
also seems off to me, as userInputCountDown should be in the future
The following example takes a slightly different approach, as it creates a "timer" that will create a target in the future (based on the input) from the current time (adding the hours, mins and seconds) and use it as the anchor point for the count down.
So, you might say, "create a 1 hour" timer, for example.
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.Timer;
class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JTextField targetHours;
private JTextField targetMins;
private JTextField targetSeconds;
private Instant futureTime;
private Timer timer;
private JLabel countDown;
public TestPane() {
setLayout(new GridBagLayout());
targetHours = new JTextField("00", 2);
targetMins = new JTextField("00", 2);
targetSeconds = new JTextField("00", 2);
JPanel targetPane = new JPanel(new GridBagLayout());
targetPane.add(targetHours);
targetPane.add(new JLabel(":"));
targetPane.add(targetMins);
targetPane.add(new JLabel(":"));
targetPane.add(targetSeconds);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.insets = new Insets(8, 8, 8, 8);
add(targetPane, gbc);
JButton btn = new JButton("Start");
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
futureTime = LocalDateTime.now()
.plusHours(Long.parseLong(targetHours.getText()))
.plusMinutes(Long.parseLong(targetMins.getText()))
.plusSeconds(Long.parseLong(targetSeconds.getText()))
.atZone(ZoneId.systemDefault()).toInstant();
if (timer != null) {
timer.stop();
}
countDown.setText("---");
timer = new Timer(500, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Duration duration = Duration.between(Instant.now(), futureTime);
if (duration.isNegative()) {
timer.stop();
timer = null;
countDown.setText("00:00:00");
} else {
String formatted = String.format("%02d:%02d:%02d", duration.toHours(), duration.toMinutesPart(), duration.toSecondsPart());
countDown.setText(formatted);
}
}
});
timer.start();
}
});
add(btn, gbc);
countDown = new JLabel("---");
add(countDown, gbc);
}
}
}
WARNING - I do NO validation on the input, so you will have to be careful.
If, instead, you wanted to count down to a particular point in time (ie count down from now to 6pm), then you would need to use LocalDateTime#withHour(Long)#withMinute(Long)#withSecond(Long) chain instead. But, beware, you'll have to verify if the time is in the future or past and take appropriate action, because if you want to countdown to 6pm, but it's 7pm ... what does that actually mean :/ ?

propertychangelistener on a JDateChooser gets triggered 2 times additionally even when the listener is detached while setting the date programatically

I am using JDateChooser for a java swing project I am developing and in this, the date could be set in two ways: by the end user or programmatically.
So I have defined a propertychangelistener in the respective class(the variable trig is initialised to zero and maintains track on how many times a property change is listened).
public class WriteEntry{
private int trig=0;
private Date currentDate = new Date();
public JDateChooser dateChooser = new JDateChooser();
public CustomDate selectedDate = DateConverter.convertDate(currentDate);
private static String filename = StorageSpace.currentpath+CurrentUser.getInstance().getUserName()+"\\"+
Integer.toString(selectedDate.getYear())+"\\"
+Integer.toString(selectedDate.getMonth())+"\\"+Integer.toString(selectedDate.getDay())+".txt";
private JLabel dayinfo = new JLabel("");
private JTextArea contentfield = new JTextArea("");
private PropertyChangeListener lis = new PropertyChangeListener(){
#Override
public void propertyChange(PropertyChangeEvent e) {
System.out.println("triggered "+trig++);
if(dateBoundary()) {
selectedDate = DateConverter.convertDate(dateChooser);
filename = StorageSpace.currentpath+CurrentUser.getInstance().getUserName()+"\\"+
Integer.toString(selectedDate.getYear())+"\\"
+Integer.toString(selectedDate.getMonth())+"\\"+Integer.toString(selectedDate.getDay())+".txt";
}
else {
updateDateChooser(selectedDate);
}
if(isAlreadyWritten())
{
try {
updateEditFields(selectedDate, "content");
} catch (IOException e1) {
e1.printStackTrace();
}
}
else
{
contentfield.setText("Start writing here");
dayinfo.setText("You are making entry for: "+ new SimpleDateFormat("dd/MM/yyyy").format(dateChooser.getDate()));
}
}
};
WriteEntry() //constructor
{
dateChooser.setDateFormatString("dd MM yyyy");
dateChooser.addPropertyChangeListener(lis);
updateEditFields(DateConverter.convertDate(currentDate), "Start");
}
}
And here is the code for dateBoundary():
public static boolean dateBoundary() {
Object[] option = {"I get it","My Bad!"};
if(dateChooser.getDate().compareTo(currentDate)>0) {
JOptionPane.showOptionDialog(HomePage.getFrame(),"message1",
"",JOptionPane.DEFAULT_OPTION,JOptionPane.ERROR_MESSAGE,null,option,option[0]);
return false;
}
if(dateChooser.getDate().compareTo(DateConverter.convertfromCustom(CurrentUser.getInstance().getDob()))<0){
JOptionPane.showOptionDialog(HomePage.getFrame(),"message2",
"",JOptionPane.DEFAULT_OPTION,JOptionPane.ERROR_MESSAGE,null,option,option[0]);
return false;
}
return true;
}
Code for isAlreadyWritten():
public static boolean isAlreadyWritten() {
File f = new File(filename);
if(f.length()!=0)
{
Object[] option = {"Read","Edit"};
JOptionPane.showOptionDialog(HomePage.getFrame(),"You already updated diary for this day. Do you want to edit?",
"",JOptionPane.DEFAULT_OPTION,JOptionPane.INFORMATION_MESSAGE,null,option,option[0]);
return true;
}
else
return false;
}
Code for updateDateChooser():
public static void updateDateChooser(CustomDate date) {
dateChooser.removePropertyChangeListener(lis); //to stop it from getting triggered when date is set programatically
dateChooser.setDate(DateConverter.convertfromCustom(date));
dateChooser.addPropertyChangeListener(lis);
}
Code for updateEditFields():
public static void updateEditFields(CustomDate searchDate, String excontent) {
updateDateChooser(searchDate);
selectedDate = DateConverter.convertDate(dateChooser);
dayinfo.setText("You are editing entry for: "+ new SimpleDateFormat("dd/MM/yyyy").format(dateChooser.getDate()));
contentfield.setText(excontent);
}
Now my dateboundary function is working as expected. whenever a date greater than current date is chosen, the optiondialog gets displayed and its gone after a click, and the datechooser is set to the last selected date, although the propertychange method is called thrice:
once before the dialog is displayed
twice after the dialog gets closed.
But my isAlreadyWritten() is not working as expected and the optiondialog is getting displayed 4 times with propertychange() method being called four times:
once before each time the dialog is displayed.
I want to understand why propertychange is being called 4 times even though the datechooser is detached from the listener when the date is set programatically?
So, I put together this quick snippet and ran it
import com.toedter.calendar.JDateChooser;
import java.awt.EventQueue;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Date;
import javax.swing.JFrame;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JDateChooser dateChooser = new JDateChooser();
dateChooser.addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent evt) {
System.out.println(evt.getPropertyName());
}
});
dateChooser.setDate(new Date());
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(dateChooser);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
I opened the date selector and selected a date. The program outputted...
date
ancestor
date
date
Was me setting the date programmatically
ancestor is it getting added to the container
Was me selecting the date picker
Was me selecting a date
So, as you can see, not only are you getting spammed with a lot of "date" property changes, you're also getting all the "other" property changes as well 😓
So, the first thing you want to do, is limit the the notifications to the "date" property only, something like...
dateChooser.addPropertyChangeListener("date", new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent evt) {
System.out.println(evt.getPropertyName());
}
});
This at least means you don't get bother by all the additional information you don't care about.
While you can add and remove the listener, I tend to find it a pain, as I don't always have a reference to the listener(s), instead, I tend to use a state flag instead
private boolean manualDate = false;
//...
dateChooser.addPropertyChangeListener("date", new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent evt) {
if (manualDate) {
return;
}
System.out.println(evt.getPropertyName());
}
});
manualDate = true;
dateChooser.setDate(new Date());
manualDate = false;
Not a big change, but this alone means that you're now down to two event notifications.
Instead, you should compare the oldValue with the newValue of the PropertyChangeEvent
JDateChooser dateChooser = new JDateChooser();
dateChooser.addPropertyChangeListener("date", new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent evt) {
if (manualDate) {
return;
}
Date newDate = (Date) evt.getNewValue();
Date oldDate = (Date) evt.getOldValue();
if (newDate != null && oldDate != null) {
LocalDate newLD = LocalDate.ofInstant(newDate.toInstant(), ZoneId.systemDefault());
LocalDate oldLD = LocalDate.ofInstant(oldDate.toInstant(), ZoneId.systemDefault());
if (newLD.equals(oldLD)) {
return;
}
}
System.out.println(evt.getPropertyName());
}
});
And now, we're down to one change event. The only draw back is it won't tell you when they reselect the current date.
A slightly better work flow might be to ignore it all and simply have a JButton that the user can press to perform what ever associated actions you need carried out
Runnable Example...
import com.toedter.calendar.JDateChooser;
import java.awt.EventQueue;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import javax.swing.JFrame;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
private boolean manualDate;
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JDateChooser dateChooser = new JDateChooser();
dateChooser.addPropertyChangeListener("date", new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent evt) {
if (manualDate) {
return;
}
Date newDate = (Date) evt.getNewValue();
Date oldDate = (Date) evt.getOldValue();
if (newDate != null && oldDate != null) {
LocalDate newLD = LocalDate.ofInstant(newDate.toInstant(), ZoneId.systemDefault());
LocalDate oldLD = LocalDate.ofInstant(oldDate.toInstant(), ZoneId.systemDefault());
if (newLD.equals(oldLD)) {
return;
}
}
System.out.println(evt.getPropertyName());
}
});
manualDate = true;
dateChooser.setDate(new Date());
manualDate = false;
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(dateChooser);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}

Prevent Sendkeys from other Application. Prevent cheating

I programmed with a little java game; the challenge is to type the hole abc in the textbox and it give out the time used.
Now i have already built in some feature to prevent cheating:
like copy paste the hole abc
or only the middle of the abc like bcdefgh...
if you study my code you will see that I only check the first lettre A, L and Z.
A to save the start time
L to prevent cheating and copy paste only the middle of the hole abc
Z to check the hole string wich i put in the TextField. And stop the time.
Heres the Code:
package lvl1;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Date;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class test implements KeyListener {
private Date start_time;
private JTextField jtf;
private JLabel lblStatus;
private boolean lpressed;
public static void main(String[] args) {
new test();
}
public test() {
jtf = new JTextField();
JFrame myframe = new JFrame();
jtf.addKeyListener(this);
lblStatus = new JLabel("Zeit:");
myframe.setSize(700, 60);
myframe.setTitle("ABC COOLGAME");
myframe.setLocationRelativeTo(null);
myframe.setDefaultCloseOperation(myframe.EXIT_ON_CLOSE);
myframe.setLayout(new GridLayout(1, 2));
myframe.add(jtf);
myframe.add(lblStatus);
myframe.setVisible(true);
}
#Override
public void keyPressed(KeyEvent arg0) {
if (65 == arg0.getKeyCode()) {
start_time = new Date();
}
if (8 == arg0.getKeyCode()) {
jtf.setText("");
jtf.setBackground(Color.WHITE);
}
if (76 == arg0.getKeyCode()) {
lpressed = true;
}
}
#Override
public void keyReleased(KeyEvent arg0) {
Date date = new Date();
if ((90 == arg0.getKeyCode()) & (jtf.getText().equals("abcdefghijklmnopqrstuvwxyz") & (lpressed == true))) {
lblStatus.setText("Zeit: " + (date.getTime() - start_time.getTime())
+ " Milliseconds");
jtf.setBackground(Color.GREEN);
lpressed = false;
}
}
#Override
public void keyTyped(KeyEvent e) {/* Nothing to do */}
}
Now I send the Jar file to my friend and in only a few minutes i reseved a message with a record of 10 milliseconds. He told me that he send with vba the hole abc over
Sleep 5000 'Here he click the cursor in my textfield
SendKeys "abcdefghijklmnopqrstuvwxyz"
this statement will send automaticly all keys seperatly in comparison similar as I typed this on my keyboard.
Anybody know a method to prevent thes technic of cheating??
the game mustnt be secure for cheat engines other something else, but to prevent the technic above will be amazing.

LWUIT Calendar date format

I have a LWUIT code that supposed to print today date .
The problem with me is the date printed in "Mon dd hh:mm:ss GMT+...... yyyy" format
e.g Thu Nov 28 01:00:00 GMT+03:00 2013
So I have a couple of questions
How to get the format in "yyyy-mon-dd" format.
how to add a day to the today date after conversion to "yyyy-mon-dd" .
Observe that some classes wouldn't work in J2ME like Simpledateformat class.
import javax.microedition.midlet.*;
import com.sun.lwuit.*;
import com.sun.lwuit.events.*;
public class myLibrary extends MIDlet {
Form f;
com.sun.lwuit.Calendar cal;
Button b;
public void startApp() {
com.sun.lwuit.Display.init(this);
f = new com.sun.lwuit.Form();
cal = new com.sun.lwuit.Calendar();
b = new Button("Enter");
f.addComponent(cal);
f.addComponent(b);
b.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent acv) {
System.out.println(""+cal.getDate());
}
});
f.show();
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
}
In order to use the java.lwuit.Calendar class, to get your date in that format you will need to substring the data from the cal.getDate().
for example
System.out.println("DAY " + cal.getDate().toString().substring(0,3));
Doing that, you will get your data and after that reorder them in a String.
To change the Date from the Calendar view you will need to use Calendar.setDate(Date d);
I suggest you to use java.util.Calendar
java.util.Calendar c = Calendar.getInstnace();
c.set(Calendar.DAY_OF_THE_MONTH, day_that_you want);
c.set(Calendar.MONTH, month_that_you want);
c.set(Calendar.YEAR, year_that_you want);
java.lwuit.Calendar cal = new java.lwuit.Calendar();
cal.setDate(c.getDate().getTime());
If you still want to use the Date class, try this code, it will print the tomorrow day
private static final int DAY = 24 * 60 * 60 * 1000;
Date d = new Date(); d.setTime(d.getTime() + DAY);
import javax.microedition.midlet.*;
import com.sun.lwuit.*;
import com.sun.lwuit.events.*;
public class myLibrary extends MIDlet {
Form f;
Button b;
public void startApp() {
com.sun.lwuit.Display.init(this);
private static final int DAY =86400000;
f = new com.sun.lwuit.Form();
b = new Button("Enter");
f.addComponent(b);
b.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent acv) {
java.util.Date d = new java.util.Date();
d.setTime(d.getTime() + DAY);
System.out.println(""+ d.toString());
}
});
f.show();
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
}

Categories