How to set JDropDown submenu with in a different location - java

I have created a JDropDown menu. I need a submenu in a different place on JFrame, basically, it's another JDropDown menu. and It shows with a condition like No dropdown menu should show at the start but after a click on any dropdown option the other dropdown menu shows, and options of that 2nd dropdown based on the main dropdown.
I have tried that code. It shows 2nd dropdown on click on any option of 1st dropdown. but If I add one more same thing with cb.setSelectedIndex(1) it can't work.
String[] choices = {"Redeem","Prepaid", "FRC","Offices","Individual Bags","Gift Subscription","E-Gift Card","My Account","Wp-Admin","Shipstaion","Any date changes"};
final JComboBox cb = new JComboBox(choices); cb.setBounds(134,200, 170,30);
cb.setSelectedIndex(0);
cb.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
try {
String[ ] choices1 = {"Redeem Remaining & Redeem Gift Card","Redeem of Tasting Kit Sub","US & NON-US Redeem","Manually Created Vouchers"};
final JComboBox cb1 = new JComboBox(choices1);
cb1.setBounds(100,250, 250,30);
JF.add(cb1);
} catch (Exception e1) { e1.printStackTrace(); }
}
});
expected result should be 2nd dropdown options shows based on the main dropdown option.

Related

Trying to hover mouse over tabs and perform automated click on a particular item in Selenium

I am trying to perform a mouse hover over a Men category tab and select "Shirts" category on this website. However I am not able to click the "shirts" category in Men item also I m not getting any error too. Here is my code:
public void PurchaseItemTest() throws InterruptedException, IOException {
Thread.sleep(3000);
//util.clickbyXpath(Constants.MENCATEGORYTAB);
WebElement element = util.getdriver().findElement(By.xpath("//a[#class='accord-header' ]"));
Actions action = new Actions(util.getdriver());
action.moveToElement(element).moveToElement(util.getdriver().findElement(By.xpath("//a[#class='accord-header' and contains(.,'Men')]"))).moveToElement(util.getdriver().findElement(By.xpath("//a[#title='Shirts']"))).click().build().perform();
This works:
final By DROPDOWN = By.cssSelector("li[class='atg_store_dropDownParent']");
final By DROPDOWN_LINK = By.cssSelector("a[class='accord-header ']");
List<WebElement> dropdowns = new WebDriverWait(util.getDriver(), 5)
.until(ExpectedConditions.presenceOfAllElementsLocatedBy(DROPDOWN));
WebElement men = dropdowns.stream()
.flatMap(dropdown -> dropdown.findElements(DROPDOWN_LINK).stream())
.filter(link -> link.getText().equals("MEN"))
.findFirst()
.orElse(null);
if(men != null) {
new WebDriverWait(util.getDriver(), 5)
.until(ExpectedConditions.elementToBeClickable(men));
Actions action = new Actions(util.getDriver());
action.moveToElement(men).build().perform();
new WebDriverWait(util.getDriver(), 5)
.until(ExpectedConditions.elementToBeClickable(SHIRTS))
.click();
}
Your xpath for the Men category tab was acting wonky for me. When you hover, make sure to wait for the "Shirts" link to be clickable before clicking. Also, avoid using Thread#sleep() with Selenium. Use Explicit Waits instead.

Multi select drop down

I am writing code for multi select using selenium(java) where i need the following task to be performed :
select multiple options in drop down
to click on button first selected which will print the first selected option from drop down.
to click on button get all selected which will print the all selected options in order .
I have this code which returns me undefined as a result for 2nd task.
public class MultipleSlectList {
public static WebDriver driver ;
#BeforeTest
public void startbrowser () throws Exception {
System.out.println("launching browser");
System.setProperty("webdriver.gecko.driver", "H:\\Selenium3\\geckodriver-v0.19.1-win32\\geckodriver.exe");
driver = new FirefoxDriver();
driver.get("http://www.seleniumeasy.com/test/basic-select-dropdown-demo.html");
}
#Test
public void selectlist () throws Exception {
WebElement ele1 = driver.findElement(By.id("multi-select"));
Select se= new Select(ele1);
se.selectByValue("New Jersey");
Thread.sleep(2000);
se.selectByValue("Texas");
Thread.sleep(2000);
se.selectByValue("Florida");
Thread.sleep(2000);
//Thread.sleep(10000);
WebElement btn1= driver.findElement(By.id("printMe"));
btn1.click(); // it is supposed to return New Jersy
WebElement firstOption = se.getFirstSelectedOption();
System.out.println("The First selected option is::" +firstOption.getText());
List <WebElement> oSize = se.getAllSelectedOptions();
int iListSize = oSize.size();
// Setting up the loop to print all the options
for (int i = 0; i < iListSize; i++)
{
// Storing the value of the option
String sValue = oSize.get(i).getText();
// Printing the stored value
System.out.println(sValue);
}
}
}
Please help me to proceed further.
I have tried with jquery as well but no luck .The result is same as "undefined" in both case .
Thanks !
Steps to select all dropdown options:
Find the SELECT WebElement by webdriver.
Create Select class which is used to operate dropdown list.
Get all options list in the dropdown list.
Loop the options list, get each option value and use
Select.selectByValue(optionValue) to select it.
Then all the dropdown option has been selected.
Below article has the code example to implement above scenario.
http://www.dev2qa.com/select-dropdown-list-selenium-webdriver/

Stopping MouseMoved Event in Java

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.

IE11 actions.moveToElement() is not working

In an specific Env. the workflow is as following:
Click on the "Main Menu"->Drop Down list opens
Click "Build" from drop down->another sub menu opens beside
Click "Edit" then
Now the following given selenium code is correctly executing on Chrome and Firefox but not in IE11.
//Main Menu opens then-->
WebElement build = driver.findElement(By.linkText("Build"));
Actions actions = new Actions(driver);
actions.moveToElement(build);
actions.click();
actions.build().perform();
Thread.sleep(2000);
WebElement edit = driver.findElement(By.linkText("Edit"));
edit.click();
Now problem is as follows:
In IE11, the moveToElement(build) not actually performing. So after clicking the "Main Menu" it stops at that position only. The main menu keeps opening there but not clicking the next option that is "Build"
Had the problem like this one
InternetExplorerOptions options = new InternetExplorerOptions();
options.EnablePersistentHover = false;
IWebDriver driver = new InternetExplorerDriver(options);
The key is:
options.EnablePersistentHover = false;
Regarding the problem with holding on the menu item to display child menu:
Seems, you've been using this approach:
WebElement edit = driver.findElement(By.linkText("Edit"));
edit.click();
Try the same. For example:
WebElement build = driver.findElement(By.linkText("Build"));
Thread.sleep(1000);
build.click();
Thread.sleep(1000);
WebElement edit = driver.findElement(By.linkText("Edit"));
edit.click();
After try to remove Thread::sleep rows. It is like a hardcode and you may use this approach:
WebDriverWait wait = new WebDriverWait(driver, timeoutInSeconds);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.linkText("Edit"));

How to remove row from Different JTables with Single Remove Button

I have a Tabbed Layout in my application
Please see this Image
So as you can see in the above Image I've 2 Tables in 2-different Tabs in first tab (SALON STOCK tab)
i want to remove the selected row
what did is : removebutton's actionPerformed Method
int row_num =jTable4.getSelectedRow();
try{dtm_stock.removeRow(row_num);}
catch(ArrayIndexOutOfBoundsException e){
JOptionPane.showMessageDialog(this,"Please select a Product");
}
this works fine for the current tab(SALON TAB)
but how to implement same for the other Tab (Stock for Sale).
Further Details :
I have 2-table in the 2-diff tabs and bothe have 2-different TableModel (Default)
at initialization the data is set to null
after that the Data is retrieved from database and set to the corresponding TableModel.
now there is a remove button which will remove the selected row from table
i want to remove the selected row from tables irrespective of any Tab
CODE : initialization
jTable4 = new javax.swing.JTable();
dtm_stock = new DefaultTableModel(new Object [][] {
{null,null, null, null},
{null,null, null, null}
},
new String [] {
"ID","NAME", "PRICE", "QUANTITY"
});
jTable4.setModel(dtm_stock
);
ADDING DATA :
//-----ADD STOCK TO THE STOCK TABLE --------------//
try {
ResultSet r7 = con.createStatement().executeQuery("select * from stock");
while(r7.next()){
dtm_stock.insertRow(dtm_stock.getRowCount(),new Object[]{r7.getString("id"),r7.getString("p_name"),r7.getString("price"),r7.getString("qty")});
}
} catch (SQLException e) {
JOptionPane.showMessageDialog(this,e.toString());
}
if i'm adding the same TableModel to the other Table then the data goes to that table and the current goes blank:
this seems to have did the trick :`
int selectedIndex = jTabbedPane2.getSelectedIndex();
if(selectedIndex == 0 ){
int row_num =stock_table.getSelectedRow();
try{
dtm_stock.removeRow(row_num);
}
catch(ArrayIndexOutOfBoundsException/*|SQLException*/ e){
JOptionPane.showMessageDialog(this,"Please select a Product");
}
}//if
if(selectedIndex == 1){
int row_num =sale_Stock_table.getSelectedRow();
try{
dtm_sale_stock.removeRow(row_num);
}
catch(ArrayIndexOutOfBoundsException/*|SQLException*/ e){
JOptionPane.showMessageDialog(this,"Please select a Product");
}
}
from here :
enter link description here
if they share same model how can they have different data, please explain
You can control which columns to display in the view (JTable).
Look at the removeColumn(...) method of JTable. It removes a column from the view. However the data is still in the TableModel.
If I understand corectly you can put some flag which will hold value for current visible tab and use if statment to remove row from correct Model. On the other hand better solution would be creating some kind of controller. The controller would store active tab, and would have removeRow method. Switching tab would trigger event so controller would know from which tab delete row.

Categories

Resources