How to set date picker initial value? - java

I have a date_picker from toedter.com from jcalendar package which are swing components. How can I set an initial value to it? I'm using netbeans.
I added the date_picker on design view and tried this on my source code :
UtilDateModel model = new UtilDateModel();
model.setDate(2014, 8, 24);
model.setSelected(true);
but I've been playing around where to put it still doesn't seem to work.
Any idea guys?

You can try this out :
String dateValue = "initial date value"; // must be in (yyyy- mm- dd ) format
Date date = new SimpleDateFormat("yyyy-mm-dd").parse(dateValue);
jDateChooser.setDate(date);

This should solve it:
UtilDateModel model = new UtilDateModel();
model.setDate( 2014, 8, 24 );
startDatePicker = new JDatePickerImpl(
new JDatePanelImpl( model ), new DateLabelFormatter() );

Related

How to deal with datepicker in Appium Android

My android application is using datepicker but i am not able to select date through datepicker. I used following code in application for datepicker but it does not work.
List<WebElement> pick = driver.findElements(By.className("android.widget.EditText"));
pick.get(0).sendKeys("21");
pick.get(1).sendKeys("Mar");
pick.get(2).sendKeys("1989");
Swipe method will help you to scroll calendar dates , Make sure that you have added Java-client JARs to your project then only swipe method will support.
Example :
First click on your calendar icon and then use following code :
Thread.sleep(5000);
for(int y=0;y<3;y++)
{
driver.swipe(350,511,350,577,0);
}
Swipe Syntax :
driver.swipe(startx, starty, endx, endy, duration);
Note : Above in code I have used sample co-ordinates so you change it according to your need. You can get exact co-ordinates from bound values of that date picker.
I have used loop in above code as I want to swipe 3 times , so it is something like if current date is 1st may then it will swipe till 4th may.
you can modify loop as per your need.
I have used Xpath to perform Datepicker action & it is working properly.
driver.findElement(By.xpath("//android.widget.NumberPicker[#index='0']")).sendKeys("Jan");
driver.findElement(By.xpath("//android.widget.NumberPicker[#index='1']")).sendKeys("24");
driver.findElement(By.xpath("//android.widget.NumberPicker[#index='2']")).sendKeys("1987");
For all the user who are still finding the way to select date can use the below code. I am using this code and working perfectly for me. It will work for calendar attached.
do {
WebElement source = driver.findElement(By.xpath("//android.view.View[#instance='0']"));
WebElement destination = driver.findElement(By.xpath("//android.view.View[#instance='22']"));
TouchAction action = new TouchAction((PerformsTouchActions)driver);
System.out.println("Dragging item");
action.longPress(source).moveTo(destination).release().perform();
boolean bul = driver.findElementsByXPath("//android.view.View[#content-desc='24 January 2018']").isEmpty();
} while(bul!=false);
driver.findElementByAccessibilityId("24 January 2018").click();
NOTE: I used drag and drop touch action to scroll and this will scroll uptill given date is not found. I just selected same years previous month date. You can use same touch action to select desired year.
I wanted to do the same thing, but for a "calendar" mode DatePicker instead of the "spinner" mode. This is my solution, which has been working fine for me.
from datetime import datetime
datePickerYearTextViewXpath = "//android.widget.TextView[#resource-id='android:id/date_picker_header_year']"
# initialize your appium driver here
driver = getAppiumDriver()
# define some screen dimensions
screenSize = driver.get_window_size()
halfScreenWidth = screenSize['width'] // 2
halfScreenHeight = screenSize['height'] // 2
def getDatePickerCurrentDate(driver):
yearTextView = driver.find_element_by_xpath(datePickerYearTextViewXpath)
yearString = yearTextView.text
dateTextView = driver.find_element_by_xpath("//android.widget.TextView[#resource-id='android:id/date_picker_header_date']")
dateString = dateTextView.text
fullDateString = '{}, {}'.format(dateString, yearString)
currentDate = datetime.strptime(fullDateString, '%a, %b %d, %Y').date()
return currentDate
def setDatePickerDate(driver, targetDate):
# driver is an appium driver
# targetDate must be a datetime.date, not a datetime
currentDate = getDatePickerCurrentDate(driver)
if targetDate.year != currentDate.year:
yearTextView = driver.find_element_by_xpath(datePickerYearTextViewXpath)
yearTextView.click()
# you may need to adjust the following numbers
# depending on your screen size
swipeAmountPerYear = 49
yearsPerScreen = 8
swipeDuration = 400
yearOffset = targetDate.year - currentDate.year
# if target year is older, swipe up (negative)
swipeDirection = -1 if yearOffset < 0 else 1
swipeVector = yearsPerScreen * swipeAmountPerYear * swipeDirection
while True:
elements = driver.find_elements_by_xpath("//android.widget.TextView[#resource-id='android:id/text1']".format(targetDate.year))
found = False
for element in elements:
if element.text == str(targetDate.year):
element.click()
found = True
break
if found:
break
else:
driver.swipe(halfScreenWidth, halfScreenHeight, halfScreenWidth, halfScreenHeight - swipeVector, swipeDuration)
currentDate = getDatePickerCurrentDate(driver)
if targetDate.month != currentDate.month:
monthOffset = targetDate.month - currentDate.month
prevOrNext = 'prev' if monthOffset < 0 else 'next'
prevOrNextButtonXpath = "//android.widget.ImageButton[#resource-id='android:id/{}']".format(prevOrNext)
for i in range(abs(monthOffset)):
driver.find_element_by_xpath(prevOrNextButtonXpath).click()
targetDateContentDescription = targetDate.strftime('%d %B %Y')
driver.find_element_by_xpath("//android.view.View[#resource-id='android:id/month_view']/android.view.View[#content-desc='{}']".format(targetDateContentDescription)).click()
currentDate = getDatePickerCurrentDate(driver)
if currentDate != targetDate:
raise ValueError('Unable to set date picker({}) to target date({})!'.format(currentDate, targetDate))
Check if this helps
driver.FindElement(By.Id("com.eos.eos_du_su:id/ed_manufdate")).Click();
((AndroidElement)(driver.FindElement(By.XPath("//android.widget.NumberPicker[#index='0']//android.widget.Button[#index=0]")))).Tap(1, 2);
((AndroidElement)(driver.FindElement(By.XPath("//android.widget.NumberPicker[#index='1']//android.widget.Button[#index=0]")))).Tap(1, 2);
((AndroidElement)(driver.FindElement(By.XPath("//android.widget.NumberPicker[#index='2']//android.widget.Button[#index=0]")))).Tap(1, 2);
driver.FindElement(By.Id("android:id/button1")).Click();

Wicket change label/textfield value

I am trying to learn Wicket. One of the problems I encounter, is changing the values of components like a label.
This is how I declare the label:
Label message = new Label("message", new Model<String>(""));
message .setOutputMarkupId(true);
add(message );
The only solution I can find:
Label newMessage= new Label(message.getId(), "MESSAGE");
newMessage.setOutputMarkupId(true);
message.replaceWith(newMessage);
target.add(newMessage);
Is there a better/easier way to edit the value of a Wicket label and display this new value to the user?
Thanks!
I think you did not understand what Models are. Your example could be rewritten as follows
Model<String> strMdl = Model.of("My old message");
Label msg = new Label("label", strMdl);
msg.setOutputMarkupId(true);
add(msg);
In your ajax event
strMdl.setObject("My new message");
target.add(msg);

AFreeChart OHLCDataset: how to remove spaces where no data at date axis?

There are no data at 9th-10th march, is it possible to remove space between this period?
If it is weekend data that produces the gaps you can do something like this
SegmentedTimeline timeline = SegmentedTimeline.newMondayThroughFridayTimeline();
((DateAxis) chart.getXYPlot().getDomainAxis()).setTimeline(timeline);
or
final OHLCDataset dataset = new DefaultOHLCDataset("Series1", ohlc);
SegmentedTimeline timeline = SegmentedTimeline.newMondayThroughFridayTimeline();
chart = ChartFactory.createHighLowChart(this.getTitle(),xLabel, yLabel,dataset,timeline, false);
If it is not the weekend then you will have to be a little more clever with the SegmentedTimeline api
http://www.jfree.org/jfreechart/api/javadoc/org/jfree/chart/axis/SegmentedTimeline.html

java to excel date formatting

The problem is when I'm running my application and have a grid (with strings and date columns) and save it as an excel file.
When I save it for the first time everything is correctly formatted, but when I try to save the same exact grid again a second time, the date formatting is gone (it's just a float value that when i right click and format to a dateTime object works). When I restart my app it will work again for the first time, then lose formatting again
the code looks like this:
Calendar calendar = Calendar.getInstance();
calendar.setTime((Date)data);
Date gmtDate = new Date(((Date) data).getTime() + (calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET)));
writableCell = new jxl.write.DateTime(sheetColumn, sheetRow, gmtDate, jxl.write.DateTime.GMT);
cellFormat = new jxl.write.WritableCellFormat (new jxl.write.DateFormat("m/d/yyyy h:mm");
writableCell.setCellFormat(cellFormat);
sheet.addCell(writableCell);
I kept break-pointing and everything is as it should be (it always knew it was a dateTime type before going in to the sheet), so I don't think it's from the code.
Has anyone else run into this issue?
Try to define a static WritableCellFormat which takes care of the date formatting.
// Required classes.
import java.util.TimeZone;
import jxl.write.DateFormat;
import jxl.write.DateTime;
import jxl.write.WritableCellFormat;
// Defined once.
public static final WritableCellFormat DATE_CELL_FRMT;
static {
DateFormat df = new DateFormat("MM/dd/yyyy hh:mm");
df.getDateFormat().setTimeZone(TimeZone.getTimeZone("GMT"))
DATE_CELL_FRMT = new WritableCellFormat(df);
}
// Usage
writableCell = new DateTime(sheetColumn, sheetRow, gmtDate, DATE_CELL_FRMT);
Try this:
cellFormat = new jxl.write.WritableCellFormat (new jxl.write.DateFormat("MM/dd/yyyy hh:mm");
It seems that your question is similar to "jExcelApi - cell date format reusing doesn't work". Probably, answer for that question help you with your problem.
Retelling of answer:
According to FAQ (question: "I'm getting the error message 'too many different cell formats'") formats cannot be reused in different sheets because they are not designed to be reused this way
In your case, code may be like this:
WritableCellFormat format = new jxl.write.WritableCellFormat(new jxl.write.DateFormat("m/d/yyyy h:mm"));
for(java.util.Date date : someDateList){
WritableCell cell = new jxl.write.DateTime(someColumn, someRow, date, format);
sheet.addCell(cell);
}

SmartGwt ListGrid.setAlwaysShowEditors(true) issue

We have basic ListGrid where one of the fields is editable and editor for this field always should be displayed, here is creation code
ListGrid listPanel = new ListGrid();
listPanel.setDataFetchMode(FetchMode.PAGED);
listPanel.setDataSource(datasource);
listPanel.setAutoFetchData(true);
listPanel.setAlwaysShowEditors(true);
listPanel.setCanEdit(true);
listPanel.setAutoSaveEdits(false);
listPanel.setSaveByCell(false);
listPanel.setEditOnFocus(true);
listPanel.setEditEvent(ListGridEditEvent.CLICK);
editable field is created here
ListGridField manualScoreColumn = new ListGridField("score", "Score");
manualScoreColumn.setType(ListGridFieldType.INTEGER);
manualScoreColumn.setCanEdit(true);
manualScoreColumn.setValidateOnChange(true);
manualScoreColumn.setValidators(new IntegerRangeValidator());
problem is when data in ListGrid is filtred using
listPanel.setCriteria(criteria);
we get such exeption
12:42:31.204:RDQ2:WARN:Log:TypeError: _5 is null
ListGrid._clearingInactiveEditorHTML() # adminApp/sc/modules/ISC_Grids.js:1530
GridBody.redraw(_1=>false) # adminApp/sc/modules/ISC_Grids.js:889
[c]Canvas.clearRedrawQueue() # adminApp/sc/modules/ISC_Core.js:3300
[c]Class.fireCallback(_1=>{Obj}, _2=>undef, _3=>[object Array], _4=>{Obj}, _5=>true)
# adminApp/sc/modules/ISC_Core.js:299
Timer._fireTimeout("$ir2251") # adminApp/sc/modules/ISC_Core.js:1269
unnamed() # adminApp/sc/modules/ISC_Core.js:1264
unnamed() #
I've found similar question here and here but no solution was proposed.
Are there any workarounds ? Thanks.
Make sure you have set ListGridField to ListGrid
listPanel.setFields(manualScoreColumn);
Another way to set editor of your choice to ListGridField is to use setEditorType method
ListGrid listPanel = new ListGrid();
listPanel.setCanEdit(true);
listPanel.setAutoSaveEdits(false);
//You can use any formitem instead of date item,Say TextItem,SelectItem etc
DateItem dateItem = new DateItem();
ListGridField dateListGridField= new ListGridField("date", "Date");
dateListGridField.setEditorType(dateItem);
listPanel.setFields(dateListGridField);

Categories