ShowOptionDialog cancel option doesn't work - java

I am trying to create a GUI for my program. This particular GUI uses a JOptionsPane with a showOptionDialog. I have added a panel to that OptionsPane that has some action listeners as well as two lists and some other things, that really doesn't matter for this question though.
Quite simply I want my showOptionDialog to perform some action when the user clicks the "cancel" button. (It will basically end the program but it must be done in a certain way). Right now when the user clicks "cancel" the program continues as if the user just ended that dialog but no action is taken. I am trying to change a variable if they click cancel which will prevent the rest of the program from running. I tested with a System.out.println to see if my value was really being changed and I found that the step wasn't occurring at all. So I would like to know based upon this code what I am doing wrong. What do I need to do to make the code run correctly when the user clicks cancel?
I do not have more code to show as my program is very large and it is impossible for me to isolate this situation.
Thanks in advance for the help!
public static void displayGUI(){
int result = JOptionPane.showOptionDialog(null, getPanel(),"JOptionPane Example : ", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, new String[]{"Confirm","Create Return"}, "default");
if(result == JOptionPane.CANCEL_OPTION){
initialScreenDecisions="NONE";
MainWriter.finishedCounter=true;
System.out.println(MainWriter.finishedCounter);
while(MainWriter.entryDetails.size()>0){
MainWriter.entryDetails.remove(0);
}
while(output.size()>0){
output.remove(0);
}
}
}
*This part of the code isn't being executed, even if the user selects cancel:
if(result == JOptionPane.CANCEL_OPTION){
initialScreenDecisions="NONE";
MainWriter.finishedCounter=true;
System.out.println(MainWriter.finishedCounter);
while(MainWriter.entryDetails.size()>0){
MainWriter.entryDetails.remove(0);
}
while(output.size()>0){
output.remove(0);
}
}

From your Question:
*This part of the code isn't being executed, even if the user selects cancel:
Try The integer value that is returned from the JOptionPane.showOptionDialog(). 0 Is returned if OK is selected and 1 is returned if Cancel is selected.
Modify your code as follows:
if(result == 1){
initialScreenDecisions="NONE";
MainWriter.finishedCounter=true;
System.out.println(MainWriter.finishedCounter);
while(MainWriter.entryDetails.size()>0){
MainWriter.entryDetails.remove(0);
}
while(output.size()>0){
output.remove(0);
}
}
Let me Know, If this doesn't Helps you!!!

You are telling JOptionPane to create two buttons ("Confirm" and "Create Return"), and then telling it the default button is "default" but you don't have a button with text "default". You also don't have a Cancel". The return value will be 0 if the uses picks "Confirm", or 1 if the user picks "Create Return", or CLOSED_OPTION if the user just closes the dialog.

If you take a look at the JavaDocs for JOptionPane.showOptionDialog, it tells you
Returns: an integer indicating the option chosen by the user, or
CLOSED_OPTION if the user closed the dialog
This is the index of the options array you passed to the method. In this case new String[]{"Confirm","Create Return"}
So a return value of 0 will mean Confirm was selected and 1 will mean Create Return was selected (or JOptionPane.CLOSE_OPTION if the user closed the window)

When assigning result a value you are using JOptionPane.OK_CANCEL_OPTION but in the if condition you are checking for JOptionPane.CANCEL_OPTION

Related

Checkbox is not checked, even though I do it with code

I'm writing a Java Game similar to Tetris for a school project. In the game I have a checkbox to turn music on/off.
My problem is that the checkbox, even though I set it to be checked, is NOT checked when I click it (don't understand me wrong, not AFTER, but before/at the same moment when I clicked it).
Okay so, in my code where I first initialize the checkbox I set it to be checked based on a variable provided in another class.
I tried debugging everything that is going on with the checkbox but I didn't get anything I didn't already knew.
Here's the code where I initialize the box:
music_cbox = TexturesHandler.getCheckboxTemplate();
music_cbox.setName("Music");
music_cbox.addMouseListener(Retris.getButtonHandler());
music_cbox.setLocation(Retris.WIDTH / 2 - 25, 250);
// Setting it to checked based on the variable
if(!Retris.getAudioHandler().canPlay()) {
music_cbox.setIcon(TexturesHandler.getUncheckedCheckBoxStyle());
music_cbox.setSelected(false);
System.out.println("box not selected");
} else {
music_cbox.setIcon(TexturesHandler.getCheckedCheckBoxStyle());
music_cbox.setSelected(true);
System.out.println("box selected");
}
The canPlay variable only gets changed when you CLICK the box:
if(box.isSelected()) {
Retris.getAudioHandler().canPlay(false);
Retris.getAudioHandler().stopMusic();
System.out.println("Music disabled");
box.setIcon(TexturesHandler.getUncheckedCheckBoxStyle());
break;
// (in a switch statement)
} else {
Retris.getAudioHandler().canPlay(true);
Retris.getAudioHandler().startMusic("Main_Menu.wav", "Main Menu", 0.1F);
System.out.println("Music enabled");
box.setIcon(TexturesHandler.getCheckedCheckBoxStyle());
break;
}
I also tried box.setSelected() after setting the new icon and all, but somehow when i first click the box, it does the else part instead of the if part.
Not sure if this helps but I noted that in the initialization you call music_cbox.setSelected() but then in your if statement you call box.isSelected()
Are these the same box? Could explain why you set the variable but then check another one.

Selenium Java handle object(alert dialog) exception without delaying. (unpredictable Java pop-up)

Goal: alert pop up. whether it's shown or not, I want it to continue. if it shows, have to select the checkbox, and hit continue. if not, ignore.
Blocker: if alert shows, it will handle the action and dialog will be closed. but when it's not, selenium hangs there without handling condition when it's not shown.
background: I use UFT before, maybe my logic could be wrong.
the pop up is application alert(not systems), so assumed "switch to(),accept()/dismiss() won't work. and I will add handle alert right after login and within the login method below.
Selenium framework background. : we use selenium maven framework, serenity BDD. object is set at the beginning of the page. and serenity.properties handle the time out default and so on.
Pop up objects (if it appears):
#FindBy(xpath = "//input[#id='notification-ack']")
private WebElement PcoNoticeChbx; //this is a check box, needs to be checked
#FindBy(xpath = "//button[contains(.,'Continue')]")
private WebElement PcoNoticeContinueBtn;//button to close the alert
*Log in method *
public void loginIntoExtApplication(String baseURL, String loginURL, String uId, String pwd, String extAppEnv)throws Exception {
gotoExtLoginPage(baseURL, loginURL);
enterLoginCredential(uId, pwd);
openAt("https://" + extAppEnv + ".programportaltest.hrsa.gov/sdms-
extranet/index.xhtml");
My Approaches:
//1.
if (PcoNoticeChbx!=null) {
PcoNoticeChbx.click();
PcoNoticeContinueBtn.click();
} else {
System.out.println("Dialog didn't display, no need any action");
}
//2. hanged here after login actions.
if(!getDriver().findElements(By.xpath("//*[#id='submit']")).isEmpty()){
PcoNoticeChbx.click();
PcoNoticeContinueBtn.click();
}
else {
System.out.println("Dialog didn't display, no need any action");
}
//3. added to watch doesn't work, it shows pending, below code failed too. I ran my Maven in Junit in debug mode. it used to work fine. but watch elements always show (pending)..
boolean isPresent = getDriver().findElements(By.id("noticebox")).size() >0
System.out.println("the diaolog exist= " + isPresent);
//4. even tried the try-catch method.
try{
PcoNoticeChbx.click();
PcoNoticeContinueBtn.click();
}catch (Exception e){
// Printing logs for my report
Log.error("Report Category button element is not found.");
// After doing my work, now i want to stop my test case
throw(e);
}
return;
}
//5. tried list webelemets:
List temp = webdriver.findElements(org.openqa.selenium.By.id("noticebox"));
if (temp.Count > 0 && temp[0].Displayed) {
// script to execute if element is found
} else {
// continue the test
}
//6. and below
if (!WebDriver.findElements(By.xpath("//*[#id='submit']")).isEmpty()==true);
{
        //handle the dialog
    }
else{
//continue
}
// 7.tried with a boolean value, but it also hangs on here first steps
boolean Nbox = PcoNoticeChbx.isDisplayed(); {
if (Nbox==false)
{
System.out.println("Dialog didn't display, no need any action");
}
else if (Nbox==true) {
PcoNoticeChbx.click() ;
PcoNoticeContinueBtn.click();
}
If this is like the popups that I've dealt with they work like this:
Customer comes to site and the site checks for the existence of a cookie. If that cookie exists, the popup is never launched (ideal state). If that cookie does NOT exist (typical state), after a specified period of time a popup appears.
Customer dismisses the popup and a cookie is created with an expiration time
Once that expiration time passes, the cookie expires and the popup will fire again
You need to do some investigation and find the cookie that is created once the popup is dismissed. Clear your cache, browse to the site, and note all the cookies that exist. Wait for the popup and dismiss it. Now find the cookie that was just created and examine it. This is the cookie you need to create. There are a lot of tutorials on creating cookies. It's pretty straightforward.
Once you learn how to create the cookie, you add it to your script as described below:
Navigate to some page on the domain that you know doesn't exist, e.g. www.domain.com/some404page. We do this because it won't trigger the popup countdown and we need to be on the domain to create the cookie.
Create the cookie
Do your normal test
No more popups.
Solution found for my case.
this maybe very easy. but takes some times for me to research. hopefully it will help you.
after use of many methods, for this javascripts confirmation alert. i have used below method. all of help of .CurrentlyVisible() method. because this one, and i guess only this one will give you result even when the element does not exist or null..
if (element(NoticeContinueBtn).**isCurrentlyVisible**()==true) {
PcoNoticeChbx.click();
PcoNoticeContinueBtn.click();
//else just continue
}

How can I exit this loop?

I'm a beginner and can't work out why this loop won't break.
I need to delete some users and for each user i'm prompted if i'm sure i want to delete the user.
so i made the following loop:
while (!alert && delete_button_is_present)
{
clickDeleteBtn;
if(alert)
{
driver.switchTo().alert().accept();
}
else if(delete_button_is_not_present)
{
break;
}
}
Problem is after all users are deleted and delete button is not present anymore the test is still looking for the button.
Make sure delete_button_is_present is or at least can be modified in either clickDeleteButton or driver.switchTo().alert().accept(), or that condition can never be met.
Some questions I have about your code though, which might help if they get cleaned up: you have delete_button_is_present and delete_button_is_not_present. You can get rid of not_present and just use !delete_button_is_present. Why do you have an else if which isn't paired with an if inside if(alert)? If you mean for this to be if(alert), then if(!delete_button_present) then you just need an if statement. Otherwise you want that else if outside the if(alert).
Lets walk through your code
while (!alert && delete_button_is_present)
{
clickDeleteBtn;
if(alert)
{
driver.switchTo().alert().accept();
else if(delete_button_is_not_present)
{
break;
}
}
You're saying that you want to continue this loop as long as there is no alert, and there is a delete button present on the screen. First, you click the delete button. Without any information about what this button does, I'll assume it is not relevant to the loop. You say if(alert), but if there was an alert you wouldn't be in the loop in the first place...So the loop repeats

Any workarounds to lack of PreSelection events in SWT/JFace?

In my application I want the user to save any changes before he leaves a tab (implemented as CTabFolder).
I tried to handle SelectionEvent, but it fires after the tab has been changed (so why does it even have a doit field? Does it fire before change for some other controls?)
Looking on Bugzilla, I've found https://bugs.eclipse.org/bugs/show_bug.cgi?id=193453 and https://bugs.eclipse.org/bugs/show_bug.cgi?id=193064, neither of which is fixed.
Since this requirement is probably common, does anybody have a workaround?
I have a workaround that works with org.eclipse.ui.part.MultiPageEditorPart which is backed by a CTabFolder. I'll adapt it for a straight CTabFolder implementation.
First off use the selection listener:
tabFolder.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
pageChange(tabFolder.indexOf((CTabItem) e.item));
}
});
Then I implement pageChange() like this:
protected void pageChange(int newPageIndex) {
boolean changingPages = this.changingPages;
this.changingPages = true;
int oldPageIndex = tabFolder.getSelectionIndex();
if (isDirty() && !changingPages) {
tabFolder.setSelection(oldPageIndex);
if (canChangePages()) {
tabFolder.setSelection(newPageIndex);
}
}
this.changingPages = false;
}
In canChangePages() I pop up a do you want to save dialog and give the user an opportunity to select yes, no, or cancel. Yes saves the info and returns true. No reverts the info to the last saved state and returns true. Cancel simply returns false. You may simply want to try saving and return false only if the save fails.
It may look weird that I switch back to the old page before calling canChangePages(). This call executes quickly so it gives the illusion the tab never switched. No matter how long canChangePages() takes the user will not see a tab change unless it is approved by that method.

In GWT, how to reset the URL when the user hits "Cancel" in the navigation confirmation dialog?

In my GWT application, I want to ask a user confirmation when he navigates out of the current application, i.e. by entering a URL or closing the browser. This is typically done by registering a ClosingHandler and setting the desired dialog message in the onWindowClosing method. This seems to work well.
However, if the user tries to navigate say to http://www.gmail.com (by typing it in the URL bar) and hits Cancel to indicate he doesn't want to navigate, then my app keeps running but the browser's URL bar keeps indicating http://www.gmail.com. This causes a number of problems later in my application and will give the wrong result if the user bookmarks the page.
Is there a way to automatically reset the URL when the user presses Cancel?
Or, alternatively, is there a way to detect the user pressed the Cancel button? If so, is there a way to set the URL without triggering a ValueChangeEvent? (I could add some logic to prevent this, but I'd rather use a built-in mechanism if it exists.)
Not sure if this works but did you try: History.newItem(History.getToken(), false); to reset the URL? It does set the history token without triggering a new history item.
I managed to do this. It looks like GWT DeferredCommand are executed after the confirmation window has been closed. This, combined with Hilbrand's answer above, give me exactly what I want. Here is exactly what I do:
public final void onWindowClosing(Window.ClosingEvent event) {
event.setMessage(onLeaveQuestion);
DeferredCommand.addCommand( new Command() {
public void execute() {
Window.Location.replace(currentLocation);
}
});
}
Where currentLocation is obtained by calling Window.Location.getHref() every time the history token changes.
I solved this by creating a custom PlaceController and replacing the token in the url. Not an ideal solution but it works!
if (warning == null || Window.confirm(warning)) {
where = newPlace;
eventBus.fireEvent(new PlaceChangeEvent(newPlace));
currentToken = History.getToken();
} else {
// update the url when user clicks cancel in confirm popup.
History.replaceItem(currentToken, false);
}

Categories