im new to Java and JavaFX and I want to create a GUI with a Label which shows the current system Time.
The Problem is: the Time Value doesn't update. So I wanted to create a Thread, that is updating my Time-Value and also the Label every 1 second with the command:
label_time_show.setText(curTime);
In the inizialize method (see code below) the "label_show_time" can be inizialized with any value, but when I try to setText in an other method I get the following Error:
Exception in thread "Thread-4" java.lang.NullPointerException
I commented the line in the Code where the Label is null and where the Label is NOT null.
Can someone help me with this Problem?
public class FXMLDocumentController implements Initializable, Runnable
{
public String curTime; // <--- main value of time (String)
#FXML
private Label label_time_show;
#FXML
private Label label_time;
// initializer
#Override
public void initialize(URL url, ResourceBundle rb)
{
java.util.Date now = new java.util.Date();
Long sysTime = now.getTime();
String sysTimeString = sysTime.toString();
Integer h = now.getHours();
Integer m = now.getMinutes();
Integer s = now.getSeconds();
String hh = h.toString();
String mm = m.toString();
String ss = s.toString();
curTime = hh + ":" + mm + ":" + ss;
label_show_time.setText(curTime); // <---- label_show_time is NOT null
}
// run method
#Override
public void run()
{
System.out.println("THREAD FXMLController running....");
while(true)
{
time();
}
}
public void time()
{
java.util.Date now = new java.util.Date();
Long sysTime = now.getTime();
String sysTimeString = sysTime.toString();
Integer h = now.getHours();
Integer m = now.getMinutes();
Integer s = now.getSeconds();
String hh = h.toString();
String mm = m.toString();
String ss = s.toString();
curTime = hh + ":" + mm + ":" + ss;
label_show_time.setText(curTime); // <---- label_show_time is null !!! throws ERROR
}
}
So, given the limited information, I'll take a blind stab at this. At the end of your initialize method your label is not null, so start your thread then.
public void initialize(URL url, ResourceBundle rb)
{
//java.util.Date now = new java.util.Date();
//Long sysTime = now.getTime();
//String sysTimeString = sysTime.toString();
//Integer h = now.getHours();
//Integer m = now.getMinutes();
//Integer s = now.getSeconds();
//String hh = h.toString();
//String mm = m.toString();
//String ss = s.toString();
//curTime = hh + ":" + mm + ":" + ss;
//label_show_time.setText(curTime); // <---- label_show_time is NOT null
//Since the label not null here, start your thread here.
new Thread(this).start();
}
Then your time method would be similar except you would post things to the Platform thread.
public void time()
{
java.util.Date now = new java.util.Date();
Long sysTime = now.getTime();
String sysTimeString = sysTime.toString();
Integer h = now.getHours();
Integer m = now.getMinutes();
Integer s = now.getSeconds();
String hh = h.toString();
String mm = m.toString();
String ss = s.toString();
curTime = hh + ":" + mm + ":" + ss;
Platform.runLater(()->{
label_show_time.setText(curTime);
});
}
You might want to put a sleep in your run method since you only need to update every second.
public void run(){
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
while (true){
Date date = new Date();
label_show_time.setText(dateFormat.format(date));
try{
TimeUnit.SECONDS.sleep(1);
}catch(InterruptedException e){
}
}
}
mb it helps you?
and init your label.
update:
public void initialize(URL url, ResourceBundle rb) {
...
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
new Thread(new Runnable() {
#Override
public void run() {
while (true){
Date date = new Date();
System.out.println(dateFormat.format(date));
try{
TimeUnit.SECONDS.sleep(1);
}catch(InterruptedException e){
}
}
}
}).start();
}
Related
I have below Java code to convert string format to Timestamp object
public class TestUtil{
Object result;
Public Object convertFormat(String format, String value, String type){
String format = "yyyyMMddHHmmss";
String value = "20050225144824";
SimpleDateFormat dformat = new SimpleDateFormat(format);
java.util.Date date = dformat.parse(value);
result = new Timestamp(date.getTime);
System.out.println("Result::"+ result);
}
}
Expected outcome:
I was expecting the outcome should be like below
20050225144824
Actual outcome:
2005-02-25 14:48:24.0
Could anyone tell me what I am missing here? To get "20050225144824" this result
The below code runs fine for me.
Adding few print statements to explain the different behaviors.
import java.util.Date;
import java.text.SimpleDateFormat;
import java.sql.Timestamp;
public class Main
{
public static void main(String[] args) {
String myFormat = "yyyyMMddHHmmss";
String value = "20050225144824";
try {
SimpleDateFormat dformat = new SimpleDateFormat("yyyyMMddHHmmss");
Date date = dformat.parse(value);
Timestamp ts = new Timestamp(date.getTime());
Object result = new Timestamp(date.getTime());
System.out.println("Timestamp Format with yyyyMMddHHmmss : " +dformat.format(ts));
System.out.println("Object Format with yyyyMMddHHmmss : " +result);
System.out.println("Object Format with yyyyMMddHHmmss : " +dformat.format(result));
} catch(Exception e) {
e.printStackTrace();
}
}
}
Here is the output of the different behaviors :
Timestamp Format with yyyyMMddHHmmss : 20050225144824
Object Format with yyyyMMddHHmmss : 2005-02-25 14:48:24.0
Object Format with yyyyMMddHHmmss : 20050225144824
If you expect Timestamp to return your custom output then you need to override the default Timestamp library.
Here I create CustomTimestamp.java to extend Timestamp and override its toString() method. I modified the changes according to your requirement.
public class CustomTimestamp extends Timestamp {
private int nanos;
public CustomTimestamp(long time) {
super(time);
}
#Override
public String toString () {
int year = super.getYear() + 1900;
int month = super.getMonth() + 1;
int day = super.getDate();
int hour = super.getHours();
int minute = super.getMinutes();
int second = super.getSeconds();
String yearString;
String monthString;
String dayString;
String hourString;
String minuteString;
String secondString;
String nanosString;
String zeros = "000000000";
String yearZeros = "0000";
StringBuffer timestampBuf;
if (year < 1000) {
// Add leading zeros
yearString = "" + year;
yearString = yearZeros.substring(0, (4-yearString.length())) +
yearString;
} else {
yearString = "" + year;
}
if (month < 10) {
monthString = "0" + month;
} else {
monthString = Integer.toString(month);
}
if (day < 10) {
dayString = "0" + day;
} else {
dayString = Integer.toString(day);
}
if (hour < 10) {
hourString = "0" + hour;
} else {
hourString = Integer.toString(hour);
}
if (minute < 10) {
minuteString = "0" + minute;
} else {
minuteString = Integer.toString(minute);
}
if (second < 10) {
secondString = "0" + second;
} else {
secondString = Integer.toString(second);
}
if (nanos == 0) {
nanosString = "";
} else {
nanosString = Integer.toString(nanos);
// Add leading zeros
nanosString = zeros.substring(0, (9-nanosString.length())) +
nanosString;
// Truncate trailing zeros
char[] nanosChar = new char[nanosString.length()];
nanosString.getChars(0, nanosString.length(), nanosChar, 0);
int truncIndex = 8;
while (nanosChar[truncIndex] == '0') {
truncIndex--;
}
nanosString = new String(nanosChar, 0, truncIndex + 1);
}
// do a string buffer here instead.
timestampBuf = new StringBuffer(20+nanosString.length());
timestampBuf.append(yearString);
timestampBuf.append(monthString);
timestampBuf.append(dayString);
timestampBuf.append(hourString);
timestampBuf.append(minuteString);
timestampBuf.append(secondString);
timestampBuf.append(nanosString);
return (timestampBuf.toString());
}
}
Your main class should use CustomTimestamp to get the output
try {
String format = "yyyyMMddHHmmss";
String value = "20050225144824";
SimpleDateFormat dformat = new SimpleDateFormat(format);
java.util.Date date;
date = dformat.parse(value);
Timestamp result = new CustomTimestamp(date.getTime());
System.out.println("Result::" + result);
} catch (ParseException e) {
e.printStackTrace();
}
I am having set of 8 images. Here the images will be flipping according to the time which is set by the user and their will be default wake up time 7:00am. If the user sets the time at 10:10pm and the wake up time is 7:00am. Now, the images needs to flip and the flipping of images are in percentage wise i.e; 0% 20% 40% 60% 80% 90% 95% 100% of the total time. Now, the images are flipping when i am setting the time from 10:00am to 7:00pm , 9:00am to 11:00am , 7:00pm to 8:30pm etc. But when i am setting from 10:00pm to 7:00am the images are not flipping.
c = Calendar.getInstance();
SimpleDateFormat displayFormat = new SimpleDateFormat("HH:mm");
SimpleDateFormat testhrFormat = new SimpleDateFormat("HH");
SimpleDateFormat testminFormat = new SimpleDateFormat("mm");
String formattedDate = testhrFormat.format(c.getTime());
int minDate = Integer.parseInt(testminFormat.format(c.getTime()));
long hrlong = TimeUnit.HOURS.toMinutes(Long.parseLong(formattedDate));
addedmin = hrlong + minDate;
twwntyhrformat = displayFormat.format(c.getTime());
SimpleDateFormat parseFormat = new SimpleDateFormat("HH:mm a");
SharedPreferences timegot = getSharedPreferences("CHILDTIME", MODE_PRIVATE);
String time = timegot.getString("savedwakeuptime", "");
try {
Date date = parseFormat.parse(time);
String gottime = displayFormat.format(date);
String[] timedivided = gottime.split(":");
String gothr = timedivided[0];
long gotlong = TimeUnit.HOURS.toMinutes(Long.parseLong(gothr));
String gotmin = timedivided[1];
int gotintmin = Integer.parseInt(gotmin);
addgottime = gotlong + gotintmin;
long subtime = addgottime - addedmin;
String submilli = String.valueOf(subtime);
long submillitimeunit = TimeUnit.MINUTES.toMillis(Long.parseLong(submilli));
final int gotflippingtime = (int) submillitimeunit;
handler = new Handler();
run = new Runnable() {
#Override
public void run() {
String number = String.valueOf(fliper.getDisplayedChild());
if (number.equals("7")) {
handler.removeCallbacks(run);
back_home.setEnabled(true);
} else {
fliper.showNext();
handler.postDelayed(run, gotflippingtime);
}
}
};
for (int gotinterval : gotintervals) {
handler.postDelayed(run, gotinterval);
}
handler.postDelayed(run, gotflippingtime);
} catch (ParseException e) {
e.printStackTrace();
}
} else {
c = Calendar.getInstance();
SimpleDateFormat testhrFormat = new SimpleDateFormat("HH");
SimpleDateFormat testminFormat = new SimpleDateFormat("mm");
String formattedDate = testhrFormat.format(c.getTime());
int minDate = Integer.parseInt(testminFormat.format(c.getTime()));
long hrlong = TimeUnit.HOURS.toMinutes(Long.parseLong(formattedDate));
addedmin = hrlong + minDate;
SharedPreferences timegot = getSharedPreferences("CHILDTIME", MODE_PRIVATE);
long numberlong = timegot.getLong("savedwakeuptime",0);
long millicurrenttime=TimeUnit.MINUTES.toMillis(addedmin);
long subtime = numberlong-millicurrenttime;
Log.d("Calc", String.valueOf(subtime)+" "+String.valueOf(numberlong)+" "+String.valueOf(millicurrenttime));
flippingtime = (int) subtime;
intervals = new ArrayList<Integer>();
intervals.add((int) (flippingtime * 0.20f));
intervals.add((int) (flippingtime * 0.40f));
intervals.add((int) (flippingtime * 0.60f));
intervals.add((int) (flippingtime * 0.80f));
intervals.add((int) (flippingtime * 0.90f));
intervals.add((int) (flippingtime * 0.95f));
intervals.add((int) (flippingtime * 1.00f));
intervals.add(flippingtime);
handler = new Handler();
run = new Runnable() {
#Override
public void run() {
String number = String.valueOf(fliper.getDisplayedChild());
if (number.equals("7")) {
handler.removeCallbacks(run);
} else {
fliper.showNext();
handler.postDelayed(run, flippingtime);
}
}
};
for (int interval : intervals) {
handler.postDelayed(run, interval);
}
handler.postDelayed(run, flippingtime);
In my java project i want to disable a range of dates in the java calendar and could not be successful. I'm using Netbeans as my IDE and JCalendar. Below is my code. Any help would be appreciated.
ArrayList<JSONObject> arrays = new ArrayList<JSONObject>();
for (int i = 0; i < n; i++) {
JSONObject another_json_object = vacation_home_booking_data.getJSONObject(i);
JSONObject[] jsons = new JSONObject[arrays.size()];
arrays.toArray(jsons);
String id = another_json_object.getString("id");
String vh_id = another_json_object.getString("vh_id");
String check_in = another_json_object.getString("check_in");
String check_out = another_json_object.getString("check_out");
String status = another_json_object.getString("status");
//creating two arrays of checking and checkout
//check_in_arr[i] = another_json_object.getString("check_in");
//check_out_arr[i] = another_json_object.getString("check_out");
System.out.println("ID is " + id + "vh id is " + vh_id + "check in is " + check_in + "check out is " + check_out);
DateFormat formatter = new SimpleDateFormat("yyyy-mm-dd");
try {
Date date1 = formatter.parse(check_in);
Date date2 = formatter.parse(check_out);
jCalendar1.setSelectableDateRange(date1, date2);
jCalendar1.setBackground(Color.yellow);
//jCalendar1.setSelectedDate();
} catch (ParseException ex) {
Logger.getLogger(Calender.class.getName()).log(Level.SEVERE, null, ex);
ex.printStackTrace();
}
}
Please see, if the below methods works for you:
private DateChooserCombochooser; // Initialize this somewhere
public void setMaxDate(Calendar aDate) {
chooser.setMaxDate(aDate);
}
public void setMinDate(Calendar aDate) {
chooser.setMinDate(aDate);
}
Alternatively, try using setDefaultPeriods(PeriodSet periods) method in the API.
In my android program, I have a spinner that allows the user to select different times. Each selection is processed with Joda time to subtract the minutes. It works fine for minutes 0 to 59 and 61 and greater. However, when 60 minutes is subtracted, the time is not updated, and the original time is shown.
How do I get Joda time to subtract 60 minutes?
Spinner:
public class MyOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id1) {
String mins = parent.getItemAtPosition(pos).toString();
int intmins=0;
// process user's selection of alert time
if(mins.equals("5 minutes")){intmins = 5;}
if(mins.equals("10 minutes")){intmins = 10;}
if(mins.equals("20 minutes")){intmins = 20;}
if(mins.equals("30 minutes")){intmins = 30;}
if(mins.equals("40 minutes")){intmins = 40;}
if(mins.equals("50 minutes")){intmins = 50;}
if(mins.equals("60 minutes")){intmins = 60;}
if(mins.equals("120 minutes")){intmins = 120;}
String stringMinutes=""+intmins;
setAlarm(intmins, stringMinutes);
} else {
}
public void onNothingSelected(AdapterView parent) {
mLocationDisplay.setText(" " + location);
}
}
public void setAlarm(int intmins, String mins) {
// based alarm time on start time of event. TODO get info from database.
String currentDate;
SimpleDateFormat myFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date date1 = null;
DateTime dt;
currentDate = eventdate + " " + startTimeMilitary;// startTimeMilitary;
try {
date1 = myFormat.parse(currentDate);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
dt = new DateTime(date1);
long dateInMillis = dt.getMillis();
String sDateInMillis = Long.toString(dateInMillis);
// subtract the selected time from the event's start time
String newAlertTime = subtractTime(dt, intmins);
newAlertTime = subtractTime(dt, intmins);
//......}
public String subtractTime(DateTime dt, int minusTime) {
DateTime greaterDate;
greaterDate = dt.minusMinutes(minusTime);
// newAlertTime is in UTC format
String newAlertTime = greaterDate.toString();
long alertInMillis = greaterDate.getMillis();
String sAlertInMillis = Long.toString(alertInMillis);
// ////new alert time is a stirng
setStringAlertInMillis(sAlertInMillis);
return newAlertTime;
}
1) Remove hardcode.
Use
final String mins = parent.getItemAtPosition(pos).toString();
final Pattern minutes = Pattern.compile("([0-9]+) minutes");
final Matcher m = minutes.matcher(mins);
String stringMinutes = "0";
if (mins.matches())
{
stringMinutes = m.group(1);
}
setAlarm(Integer.parseInt(stringMinutes), stringMinutes);
instead of your hardcode
String mins = parent.getItemAtPosition(pos).toString();
// your hardcode is here
setAlarm(Integer.parseInt(stringMinutes), stringMinutes);
2) Use DateTimeFormatter instead of SimpleDateFormatter
You get java Date using SimpleDateFormatter and create DateTime by this date.
DateTimeFormatter formatter = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss");
dt = formatter.parseDateTime(currentDate);
3) Joda works well
in this code no problem with Joda.
String subtractTime(DateTime dt, int minusTime)
should works well.
Debug you code, problem is before
if(mins.equals("5 minutes")){intmins = 5;}
if(mins.equals("10 minutes")){intmins = 10;}
//...
I am trying to remove data from hashtable for a particular date,the hashtable is of type (String,vector).Initially i am checking if hashtable contains the usrDate if yes then i need to remove all the data frm hashtable only for usrDate and add the new data that is listEvents.But the contains from hashtable for other dates should not be deleted.
listEvents.addElement(eventBean);//new data is here
for (int i = 0; i < listEvents.size();i++) {
EventData e = (EventData)listEvents.elementAt(i);
}
//checking if hashtable has given date
if (listUserEvents.containsKey(usrDate)) {
Vector info = (Vector)listUserEvents.get(usrDate);
info.addElement(eventBean);
listUserEvents.put(usrDate,info);
} else {
listUserEvents.put(usrDate,listEvents);
}
i just want to add listEvents to the hashtable for the given date,without affecting the other data in hashtable which has data for some other dates.
private Hashtable getEvents(String usrDate, String timezone) {
try {
listUserEvents = getUserInfo();
listEvents = new Vector();
Calendar calendarLocalEvent = Calendar.getInstance();
// fetches time zone
TimeZone timeZoneEvent = calendarLocalEvent.getTimeZone();
System.out.println("Time Zone first-->"
+ timeZoneEvent.getDefault());
if (timezone.equals(timeZoneEvent.getDefault())) {
;
} else {
TimeZone timeZoneChange = TimeZone.getTimeZone(timezone);
System.out.println("Time Zone change-->" +timeZoneChange);
Device.setTimeZone(timeZoneChange);
}
EventList eventList = (EventList) PIM.getInstance().openPIMList(
PIM.EVENT_LIST, PIM.READ_ONLY);
Enumeration events = eventList.items();
while (events.hasMoreElements()) {
System.out.println("in while");
Event event = (Event) events.nextElement();
if (eventList.isSupportedField(Event.START)
&& event.countValues(Event.START) > 0)
{
long start = event.getDate(Event.START, 0);
SimpleDateFormat sdf = new SimpleDateFormat(
"MMM dd,yyyy HH:mm");
SimpleDateFormat sdf_start = new SimpleDateFormat("HH:mm");
SimpleDateFormat sdf_start_min = new SimpleDateFormat("HH");
String dateString = sdf.formatLocal(start);
String timeString = sdf_start.formatLocal(start);
String hour = sdf_start_min.formatLocal(start);
SimpleDateFormat sdf1 = new SimpleDateFormat("MMM dd,yyyy");
String date = sdf1.formatLocal(start);
System.out.println("dates are :" + date +"user" + usrDate);
if (usrDate.equalsIgnoreCase(date)) {
System.out.println("dates are equal:" +date);
EventData eventBean = new EventData();
if (eventList.isSupportedField(Event.END)
&& event.countValues(Event.END) > 0) {
long end = event.getDate(Event.END, 0);
SimpleDateFormat sdform = new SimpleDateFormat(
"MMM dd, yyyy HH:mm");
SimpleDateFormat sdfTime = new SimpleDateFormat(
"HH:mm");
SimpleDateFormat sdfhr = new SimpleDateFormat("HH");
String dateString1 =sdform.formatLocal(end);
String timeString1 =sdfTime.formatLocal(end);
String hr = sdfhr.formatLocal(end);
eventBean.setStartHr(hour);
eventBean.setEndHr(hr);
eventBean.setStartTime(timeString);
eventBean.setEndTime(timeString1);
eventBean.setStartDate(dateString);
eventBean.setEndDate(dateString1);
// Dialog.alert("equal startdate" + dateString);
// Dialog.alert("equal end date"+ dateString1);
}
if (eventList.isSupportedField(Event.LOCATION)
&& event.countValues(Event.LOCATION) > 0) {
String location = event
.getString(Event.LOCATION, 0);
eventBean.setLocation(location);
// Dialog.alert("equal location"+ location);
}
if (eventList.isSupportedField(Event.SUMMARY)
&& event.countValues(Event.SUMMARY) > 0) {
String subject = event.getString(Event.SUMMARY, 0);
eventBean.setSummary(subject);
// Dialog.alert("equal subject" +subject);
}
eventBean.setUserDate(usrDate);
eventBean.setTimeZone(timezone);
listEvents.addElement(eventBean);
System.out.println("the size bf hashis"
+ listEvents.size());
for (int i = 0; i < listEvents.size();i++) {
EventData e = (EventData)listEvents.elementAt(i);
System.out.println("so thesummary is ::"
+ e.getSummary());
}
// for(int i=0;i<listUserEvents.size();i++){
if (listUserEvents.containsKey(usrDate)) {
// listUserEvents.remove(usrDate);
Vector info = (Vector)listUserEvents.get(usrDate);
System.out.println("the size in getEvents is"
+ info.size());
if(info.contains(usrDate)){
System.out.println("in info");
}
info.addElement(eventBean);
System.out.println("vector size info is"
+ info.size());
listUserEvents.put(usrDate,info);
} else {
System.out.println("in else of getevent" +listEvents.size());
listUserEvents.put(usrDate,listEvents);
}
// }
} else {
// Dialog.alert("not equal");
}
}
}
Device.setTimeZone(timeZoneEvent);
Calendar calendarLocalLastEvent = Calendar.getInstance();
// fetches time zone
TimeZone timeZoneEventLast =calendarLocalLastEvent.getTimeZone();
System.out.println("Time Zone last-->"
+ timeZoneEventLast.getDefault());
} catch (PIMException e) {
// //Dialog.alert(e.getMessage());
}
System.out.println("size in hashtable " + listUserEvents.size());
return listUserEvents;
}
It must be something like this
for(int i = 0; i<listUserEvents.size();i++)
{
if (listUserEvents.containsKey(usrDate)){
listUserEvents.remove(usrDate);
}
}
Here is a simple example of how this works:
Hashtable<String, Integer> numbers = new Hashtable<String, Integer>();
numbers.put("one", 1);
numbers.put("two", 2);
if (numbers.containsKey("two")) {
numbers.put("two", 222);
}
What are you having difficulty at? Moreover what is the type of your Hashtable key? Is it java.util.Date or something else?