I'm doing a project in school and I've a distinction feature to implement but have some issues. What I need to do is that I've to check the number of beds left in my SQL database and if it goes below a critical number a JOptionPane appears.
What I'm trying to do is another scenario which is tougher, 2 Frames opened. Eg, first frame user uses the bed, it'll drop to the critical value 10, on the other frame when the user moves his mouse arrow the JOptionPane will pop up showing a message.
I've looked up in this community but I can't seem to implement the codes to make it work. I've got to a point where there's no errors but I can't seem to close the JOptionPane. Basically I would only want this event to fire only when user of either frames go below the bed count.
I'm brand new to this actionevent. I'm doing this project as 3 tier programming with MySQL database.
I've looked at these sites but to no avail:
Stopping mouseMoved
How to temporarily disable event listeners in Swing?
Code for the Frame to show the JOptionPane
public HomePageForm() {
setTitle("Home");
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
setBounds(100, 100, 640, 428);
contentPane = new JPanel();
contentPane.addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseMoved(MouseEvent e) {
String cardioMsg = "Beds are running out for Cardiothoracic Department!";
String oncoMsg = "Beds are running out for Oncology Department!";
String orthoMsg = "Beds are running out for Orthopaedic Department!";
String pediaMsg = "Beds are running out for Pediatric Department!";
if (ignoreMouseMovedEvents) {
return;
}
ArrayList<ChangeBed> bedList = new ArrayList<ChangeBed>();
ChangeBedControl cbc8 = new ChangeBedControl();
bedList = cbc8.processCountBedsAvailableDpt4();
for (int i = 0; i < bedList.size(); i++) {
bedsForPediatric = bedList.get(i).getRowCountAvail();
}
if (bedsForPediatric <= 3) {
int valuePedia = JOptionPane.showConfirmDialog(null, pediaMsg, "URGENT", JOptionPane.WARNING_MESSAGE);
if (valuePedia == 0 || valuePedia == 2) {
ignoreMouseMovedEvents = true;
valuePedia = JOptionPane.CLOSED_OPTION;
}
}
}
});
Codes for Controller Class
public ArrayList<ChangeBed> processCountBedsAvailableDpt4() {
ChangeBed changeBed = new ChangeBed();
ArrayList<ChangeBed> bedList = new ArrayList<ChangeBed>();
bedList = changeBed.countBedsAvailableDpt4();
return bedList;
}
Entity class to retrieve from SQL DB
public ArrayList<ChangeBed> countBedsAvailableDpt4() {
ArrayList<ChangeBed> bedList = new ArrayList<ChangeBed>();
boolean rowBooleanAvail;
int rowCountAvail;
try {
myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ooadp?useSSL=false", "root", "root");
Statement myStmt = myConn.createStatement();
ResultSet myRs = myStmt.executeQuery("SELECT count(*) FROM bed WHERE bedStatus = 'Available' AND department = 'Pediatric'");
while (myRs.next()) {
rowBooleanAvail = myRs.last();
rowCountAvail = myRs.getRow();
ChangeBed cb = new ChangeBed(myRs.getInt(rowCountAvail), "");
bedList.add(cb);
}
} catch (Exception e) {
e.printStackTrace();
}
return bedList;
}
Basically I also have a Login Frame, upon logging in it opens up the frame I've shown in the above codes. At first showing a JOptionPane upon Mousemoved event showing a warning message. Once I click Ok/Cancel it closes the JOptionPane and stops the mousemoved event.
If I have another login frame whereby I login to the homepage (codes of the frame shown above), the same process will repeat whereby an optionpane will be shown.
So now I'll have 2 homepages opened and both mousemoved event deactivated and it won't fire again.
For frame 2, if I were to hit the critical value of to show the JOptionPane as soon as I move the mouse in the first homepage frame - how can I do that?
Lets answer with a question back to you: why do you want to stop the events?
Meaning: you programmed a listener that reacts to certain events. Now you are saying: at some point; I don't want "reactions"; so how do I prevent those events going into my listener?!
That is one way to look at it.
The other: simply tell your listener(s) that they should ignore incoming events, like:
Class SomeExample {
private boolean ignoreMouseMovedEvents = false;
...
#Override
public void mouseMoved(MouseEvent e) {
if (ignoreMouseMovedEvents) {
return;
}
... handle move events
Now you just need to update that boolean field whenever you want to ignore mouse move events.
But lets be precise here: I am not saying that ignoring events is always the best solution. I am merely expressing: if it is hard for you to prevent events from coming "into your system"; then maybe it is easier to let them coming; but change the way how your system reacts to them.
Finally: there is also a slightly different variation of this: instead of telling your listener to ignore events; you can also de-register your listeners from the event source. In other words: you can simply drop your listener from the frame you attached it to. And you re-add it, when events should be processed again.
Related
I have written a Java code with if-else statements and user would move from 'Screen1' to 'Screen2' through any of 4 alternate routes and I have attached an image for all possible application flows which are decided on the go by of course code written by developer. Just to add tool used is Appium.
driver.findElement(By.id("----")).click(); //this click will take from 'screen1' to next screen.
if(driver.findElement(By.id("com.abc.rbanking:id/WhatsNew")).isDisplayed())
{ //case if screen A is displayed just after screen 1
MobileElement cross = driver.findElement(By.xpath("//*[#class = 'android.widget.ImageView']"));
cross.click();
Thread.sleep(3000);
}
if(driver.findElement(By.xpath("//android.widget.TextView[#resource-id='com.abc.rbanking:id/text_logo'][text()='Security Question']")).isDisplayed())
{ //case when screen B is displayed Just after screen 1
MobileElement mfaQ = driver.findElement(By.id("com.abc.rbanking:id/MfaQuestionText"));
String question = mfaQ.getText();
String lastword = question.replaceAll("^.*?(\\w+)\\W*$", "$1");
System.out.println(lastword);
MobileElement answer = driver.findElement(By.id("com.abc.rbanking:id/MfaAnswerTextBox"));
answer.sendKeys(lastword);
MobileElement checkbox = driver.findElement(By.id("com.abc.rbanking:id/ShowChallengeAnswerCheckbox"));
checkbox.click();
Thread.sleep(3000);
MobileElement nextb = driver.findElement(By.id("com.abc.rbanking:id/PrimaryButton"));
nextb.click();
Thread.sleep(8000);
}
if(driver.findElement(By.id("com.abc.rbanking:id/WhatsNew")).isDisplayed())
{ //case when screen A is displayed after screen B
MobileElement cross = driver.findElement(By.xpath("//*[#class = 'android.widget.ImageView']"));
cross.click();
Thread.sleep(3000);
}
driver.findElement(By.id("----")); //this is code for 'Screen 2'
What happens is during execution of script, first 'If' is checked and rest all code skipped. I am not able to figure out the issue. Please help.
It sounds here as if (no pun intended) you actually don't want an if else construct. So try just using separate if statements:
// see if element on 'screen A' is displayed
if (driver.findElement(By.id("abc")).isDisplayed()) {
//execute a few statements
}
// see if element on 'Screen B' is displayed
if (driver.findElement(By.id("xyz")).isDisplayed()) {
// execute a few statements
}
// see if element on 'screen A' is displayed
if (driver.findElement(By.id("abc")).isDisplayed()) {
}
driver.findElement(By.id("----")); //this is code for 'Screen 2'
The behavior your describe, namely with the first if being hit and nothing else executing, is precisely how your code should behave. If you intend to allow for each block of code to possibly execute, then what I gave above is one option.
Finally I am able to find a solution for the problem and it is working fine. I put if statement in try-catch block like in below code and it works perfectly fine for every alternative posed by application to the end user.
try {
if (driver.findElement(By.xpath("//android.widget.TextView[#resource-id='com.abc.rbanking:id/text_logo'][text()='Security Question']")).isDisplayed()) { //case when screen B is displayed Just after screen 1
MobileElement mfaQ = driver.findElement(By.id("com.abc.rbanking:id/MfaQuestionText"));
String question = mfaQ.getText();
String lastword = question.replaceAll("^.*?(\\w+)\\W*$", "$1");
System.out.println(lastword);
MobileElement answer = driver.findElement(By.id("com.abc.rbanking:id/MfaAnswerTextBox"));
answer.sendKeys(lastword);
MobileElement checkbox = driver.findElement(By.id("com.abc.rbanking:id/ShowChallengeAnswerCheckbox"));
checkbox.click();
Thread.sleep(3000);
MobileElement nextb = driver.findElement(By.id("com.abc.rbanking:id/PrimaryButton"));
nextb.click();
Thread.sleep(8000);
}
} catch (
Exception e) {
e.printStackTrace();
}
try
{
if (driver.findElement(By.id("com.abc.rbanking:id/WhatsNew")).isDisplayed()) { //case when screen A is displayed after screen B
MobileElement cross = driver.findElement(By.xpath("//*[#class = 'android.widget.ImageView']"));
cross.click();
Thread.sleep(3000);
}
} catch (
Exception e)
{
e.printStackTrace();
}
}
In my Java application, I have a timer to keep track of how long someone does not scan a QR code. After 20 seconds, I throw a message telling them to use a manual entry instead of scan the QR code. However, how can I stop the timer once it's started? For example, a user goes to the QR scanning panel. The 20 second timer starts. The user successfully scans a QR code. Now how can I stop the timer? The timer is in my code like this.
Timer timer = new Timer();
timer.schedule( new TimerTask(){
public void run() {
//delay = 20000;
// if the timer has not been stopped, proceed with timer
if(!SpectroClick.stop_timer){
//System.out.println("20 seconds later");
//scanQRPanel.getCameraView().getWebcamPanel().pause();
stopScanning();
// Create the message to display
String text = "No QR code has been found. We suggest that you use a Manual Override." + "<br><br>" + "Press 'OK to confirm, or 'Cancel' to continue scanning for another QR code.</br>";
String message = "<html><div style=\"text-align: center;\">" + text + "</html>";
// Show the confirmation dialog screen, and wait for user input
int i = JOptionPane.showConfirmDialog((Component) null, message,
"Confirm", JOptionPane.OK_CANCEL_OPTION);
// User selected 'OK'
if (i == JOptionPane.OK_OPTION) {
for (SpectroClickEventListener listener : listeners) {
listener.userSelectedOverride();
}
}
// User did not select ok, go to new test
else{
startScanning();
}
}
}
}, delay);
I have a conditional to check if the timer is being used, however is there a way to throw some kind of exception to the timer?
The question has been already answered here.
The methods you are looking for are "cancel()" and "purge()".
I threw them into your code but haven't had a chance to run it yet:
Timer timer = new Timer();
timer.schedule( new TimerTask(){
public void run() {
//delay = 20000;
// if the timer has not been stopped, proceed with timer
if(!SpectroClick.stop_timer){
//System.out.println("20 seconds later");
//scanQRPanel.getCameraView().getWebcamPanel().pause();
stopScanning();
// Create the message to display
String text = "No QR code has been found. We suggest that you use a Manual Override." + "<br><br>" + "Press 'OK to confirm, or 'Cancel' to continue scanning for another QR code.</br>";
String message = "<html><div style=\"text-align: center;\">" + text + "</html>";
// Show the confirmation dialog screen, and wait for user input
int i = JOptionPane.showConfirmDialog((Component) null, message,
"Confirm", JOptionPane.OK_CANCEL_OPTION);
// User selected 'OK'
if (i == JOptionPane.OK_OPTION) {
for (SpectroClickEventListener listener : listeners) {
listener.userSelectedOverride();
}
}
// User did not select ok, go to new test
else{
startScanning();
}
} else{
timer.cancel();
timer.purge();
}
}
}, delay);
You shouldn't be using java.util.Timer for this, but a Swing Timer, as you're violating the single thread rules of Swing with your current approach.
A Swing Timer can be configured for a single run, which means you won't need to worry about stopping it your self
Have a look at Concurrency in Swing and How to use Swing Timers for more details
I am using Camick's code to request focus on my JPasswordField (at the end):
The focus is on the password field the first time the showConfirmDialog appears, but when the dialog appears the second time (either due to wrong password, or clicking the button again), the focus is moved to 'OK', and then back to the password field the next time. Here is my code...
int resp;
String orgPwd;
String givenPwd;
JPasswordField pwd = new JPasswordField(10);
do {
pwd.setText("");
pwd.addAncestorListener(new RequestFocusListener());
diagResp = JOptionPane.showConfirmDialog(null, pwd, "Enter Password", JOptionPane.OK_CANCEL_OPTION);
givenPwd = new String(pwd.getPassword());
if (resp != JOptionPane.OK_OPTION) { return false; }
} while (!givenPwd.equals(orgPwd));
Move pwd.addAncestorListener(new RequestFocusListener()); before the do {, you only want to add it once, not every time the loop cycles...
Also, you'll want to read and understand what the code is doing before using it.
By default the RequestFocusListener is automatically removed when the ancestorAdded event occurs, try using...
pwd.addAncestorListener(new RequestFocusListener(false));
...instead
I decided to use wizard component.link on this component
I have condition that instead of checkbox "Skip to last" I should use button. If I press on this button it's ok, but when I go to penult tab I want generate content of confirmation tab,
public void generatePreview() {
for (CompetitionTypeBean competitionType : competitionTypeList) {
if (competitionType.getId().equals(competitionTypeId)) {
tournamentBean.setCompetitionTypeBean(competitionType);
}
}
if (teamList != null && !teamList.isEmpty()) {
List<TeamBean> teams = new ArrayList<TeamBean>();
for (TeamBean team : teamList) {
for (Long teamId : teamListSelected)
if (team.getId().equals(teamId)) {
teams.add(team);
break;
}
}
tournamentBean.setTeams(teams);
}
}
it means that I should set skip in true for that I decide to write js function which will work on onnext event of wizard
<script type="text/javascript">
function setHiddenValue(formId, componentId, new_value) {
var tabId = 'competitionId';
if (tabId != 'predLast') {
document.getElementsByName('wiz').next();
} else {
var fullComponentId = formId + ":" + componentId;
document.getElementById(fullComponentId).value = new_value;
}
}
</script>
And there I find new problem
First I don't know as I can get current Tab Id. And second I don't how with help js make next event for wizard document.getElementsByName('wiz').next();. I try to see generated html code. Every tab is <li> and when this tab is selected in css style that li add 'ui-state-hightlight'
Maybe I try to develop cycle. But I can't find other solution.
To get the index of the current step in javascript, use the getStepIndex() function. To get name of the current step in the backing bean, you need to obtain a reference to the Wizard in your view and either call getStep()(returns the id property of the next tab) or getStepToProcess()(returns the actual next Tab object, from which you can get the name of the current tab).
<p:wizard/> has onnext and onback event callbacks that you can hook into to process javascript (or backing bean code with <p:remoteCommand/>)
I just add next rows in handler
public String onFlowProcess(FlowEvent event) throws Exception {
if ((skip == true)) {
skip = false; //reset in case user goes back
generatePreview();
return CONFIRM_TAB_ID;
} else {
String newTab = event.getNewStep();
if (CONFIRM_TAB_ID.equals(newTab)) {
generatePreview();
}
return newTab;
}
}
I think that using constant CONFIRM_TAB_ID it's normal, because I never decide to change this tabId.
I'm using a SWT DateTime component. It sets the current date as a default selection, when instanciated. How can i prevent this?
I want that no date is selected at all...
Thanks
Patrick
The SWT DateTime control does not support this at all.
I recommend CalendarCombo from the Eclipse Nebula project.
If this is still of use to anyone - I had the same problem, meaning that a field on the UI had to show a date or an empty value: because a date that was NOT selected was also valid input.
While SWT DateTime has to show some sort of a date, it is not a problem at all introducing another level of indirection by simply making a label and a button - too look like DateTime: The then button calls DateTime in a separate modal window. After the user has made the selection, we write the result to the label back in the application window. You also add another button to the modal window and call it e.g. NONE. If the user clicks NONE, you clear the label field in your application.
You will see that I scrape the current value of the date from the label first, so that I can initialize the DateTime control in the modal dialog. This way it all behaves like a new composite control, though I admit it is a bit awkward if you need to do it many times over. E.g.:
private Button buttonDeadlineDate;
private Label labelDeadlineDate;
// ... then define your "composite" control:
lblNewLabel_5 = new Label(group_2, SWT.NONE);
lblNewLabel_5.setBounds(10, 14, 50, 17);
lblNewLabel_5.setText("Deadline:");
// We make our own composite date control out of a label and a button
// and we call a modal dialog box with the SWT DateTime and
// some buttons.
labelDeadlineDate = new Label(group_2, SWT.BORDER | SWT.CENTER);
labelDeadlineDate.setBounds(62, 10, 76, 20);
// Note that I use the strange font DokChampa because this was the only way to get a margin at the top.
labelDeadlineDate.setFont(SWTResourceManager.getFont("DokChampa", 8, SWT.NORMAL));
labelDeadlineDate.setBackground(SWTResourceManager.getColor(255, 255, 255)); // so it does appear editable
buttonDeadlineDate = new Button (group_2, SWT.NONE);
buttonDeadlineDate.setBounds(136, 11, 20, 20); // x - add 74, y - add 1 with respect to label
// ... And later we have the call-back from the listener on the little button above:
//========================================
// Deadline Date
//========================================
buttonDeadlineDate.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
// Define the dialog shell.
// Note: DIALOG_TRIM = TITLE | CLOSE | BORDER (a typical application dialog shell)
final Shell dialog = new Shell (shlTaskScheduler, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL);
dialog.setText("Enter deadline date (NONE for none)");
//========================================
// Position and size the dialog (relative to the application).
// could have probably also used a single call to dialog.setBounds()
// instead of calling setLocation() and setSize().
//========================================
Point myPoint = new Point(0,0);
myPoint = shlTaskScheduler.getLocation();
myPoint.x +=80; // myPoint.x +=30;
myPoint.y +=320; // myPoint.y +=350;
dialog.setLocation(myPoint);
dialog.setSize(270, 220);
dialog.setLayout (null);
//========================================
// Define dialog contents
//========================================
// Make controls final they it can be accessed from the listener.
final DateTime DTDeadlineDate;
DTDeadlineDate = new DateTime(dialog, SWT.BORDER | SWT.CALENDAR | SWT.DROP_DOWN);
DTDeadlineDate.setBounds(10, 10, 175, 175);
final Button buttonNone = new Button (dialog, SWT.PUSH);
buttonNone.setText ("NONE");
buttonNone.setBounds(200, 35, 55, 25);
final Button buttonOK = new Button (dialog, SWT.PUSH);
buttonOK.setText ("OK");
buttonOK.setBounds(200, 85, 55, 25);
//========================================
// Initialize the DateTime control to
// the date displayed on the button or today's date.
//========================================
// Get the deadline from the main application window
String newDeadlineDateString = (labelDeadlineDate.getText().toString());
myLogger.i (className, "got deadline from main application window as " + newDeadlineDateString);
// If deadline date found, use it to initialize the DateTime control
// else the DateTime control will initialize itself to the current date automatically.
if ((newDeadlineDateString.length() == 10) // probably unnecessary test
&& (isThisDateValid(newDeadlineDateString, "yyyy-MM-dd"))) {
// parse and extract components
try {
String tmpYearString= newDeadlineDateString.substring(0,4);
String tmpMoString = newDeadlineDateString.substring(5,7);
String tmpDayString = newDeadlineDateString.substring(8,10);
int tmpYearInt = Integer.parseInt(tmpYearString);
int tmpMoInt = Integer.parseInt(tmpMoString);
int tmpDayInt = Integer.parseInt(tmpDayString);
DTDeadlineDate.setYear(tmpYearInt);
DTDeadlineDate.setMonth(tmpMoInt - 1); // the control counts the months beginning with 0! - like the calendar
DTDeadlineDate.setDay(tmpDayInt);
} catch(NumberFormatException f) {
// this should not happen because we have a legal date
myScreenMessage.e(className, "Error extracting deadline date from screen <" + newDeadlineDateString + ">. Ignoring");
}
} else if (newDeadlineDateString.length() > 0) {
myLogger.w (className, "Illegal current deadline date value or format <" + newDeadlineDateString + ">. Ignoring.");
// no need to do anything, as the control will initialize itself to the current date
} else {
// no need to do anything, as the control will initialize itself to the current date
}
//========================================
// Set up the listener and assign it to the OK and None buttons.
// Note that the dialog has not been opened yet, but this seems OK.
//
// Note that we define a generic listener and then associate it with a control.
// Thus we need to check in the listener, which control we happen to be in.
// This is a valid way of doing it, as an alternative to using
// addListener() or
// addSelectionListener()
// for specific controls.
//========================================
Listener listener = new Listener () {
public void handleEvent (Event event) {
if (event.widget == buttonOK) {
int newDeadlineDay = DTDeadlineDate.getDay();
int newDeadlineMonth = DTDeadlineDate.getMonth() + 1; // the returned month will start at 0
int newDeadlineYear = DTDeadlineDate.getYear();
String selectedDeadlineDate = String.format ("%04d-%02d-%02d", newDeadlineYear, newDeadlineMonth, newDeadlineDay);
if (isThisDateValid(selectedDeadlineDate, "yyyy-MM-dd")) {
labelDeadlineDate.setText(selectedDeadlineDate);
} else {
// This is strange as the widget should only return valid dates...
myScreenMessage.e(className, "Illegal deadline date selected: resetting to empty date");
labelDeadlineDate.setText("");
}
} else if (event.widget == buttonNone) {
// an empty date is also an important value
labelDeadlineDate.setText("");
} else {
// this should not happen as there are no other buttons on the dialog
myLogger.e(className, "Unexpected widget state: ignoring");
}
// once a button is pressed, we close the dialog
dialog.close ();
}
};
// Still need to assign the listener to the buttons
buttonOK.addListener (SWT.Selection, listener);
buttonNone.addListener (SWT.Selection, listener);
//========================================
// Display the date dialog.
//========================================
dialog.open ();
//========================================
// If you need to do this - you can wait for user selection before returning from this listener.
// Note that this wait is not necessary so that the above button listeners
// can capture events, but rather so that we do not continue execution and end this
// function call before the user has made a date selection clicked on a button.
// Otherwise we would just go on.
while (!dialog.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
...
}
});
You would have to manually set the fields of the instance to 0 or null whatever is appropriate. You could also implement your own NoDateTime object (using the null object pattern) to accomplish the same thing. I would be tempted to represent no time with just null though, is there a reason why you cannot do that?
One Way is to set a selection listener like in this example on Eclipse-DOC
Here is an adapted version:
private boolean isModified = false;
selectDate = new DateTime(this, SWT.DATE | SWT.DROP_DOWN);
SelectionListener selListener = new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
isModified = true;
}
};
selectDate.addSelectionListener(selListener);
Then you can do an If isModified where needed.