The following code is not working. The reportDataFields displays a list of items(for ex abc, abd, abe) and I want to select abc and drop into the target. It does not fisplay any error message either.
Actions action = new Actions(driver);
List<WebElement> reportFields = driver.findElements(By.className("reportDataFields"));
WebElement target = driver.findElement(By.id("rptDataSections"));
for (int i = 0; i < reportFields.size(); i++) {
if (reportFields.get(i).getText().equals(Section)) {
action.dragAndDrop(reportFields.get(i), target).release().build().perform();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I think you should create a new instance of Actions interface every time you use it.
Try below code with my personalized drag and drop functionality:
List<WebElement> reportFields = driver.findElements(By.className("reportDataFields"));
WebElement target = driver.findElement(By.id("rptDataSections"));
for (int i = 0; i < reportFields.size(); i++) {
if (reportFields.get(i).getText().equals(Section)) {
WebElement draggedFrom = reportFields.get(i);
new Actions(driver)
.moveToElement(draggedFrom)
.pause(Duration.ofSeconds(1))
.clickAndHold(draggedFrom)
.pause(Duration.ofSeconds(1))
.moveByOffset(1, 0)
.moveToElement(target)
.moveByOffset(1, 0)
.pause(Duration.ofSeconds(1))
.release().perform();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Related
I'm creating a utility console that does some basic key pressing for me.
But for some reason, the console view does not appear, but it is still doing its job.
This is the piece of code:
try {
Robot robot = new Robot();
int x =1;
for(int i = 0;i<10;i++){
delay();
System.out.println("Processing Bot...");
}
do{
robot.keyPress(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_TAB);
delay();
System.out.println("Key Active : Tab");
robot.keyPress(KeyEvent.VK_1);
robot.keyRelease(KeyEvent.VK_1);
for(int i = 0;i<10;i++){
delay();
}
System.out.println("Key Active : 1");
robot.keyPress(KeyEvent.VK_2);
robot.keyRelease(KeyEvent.VK_2);
for(int i = 0;i<10;i++){
delay();
}
System.out.println("Key Active : 2");
}while(x!=0);
...
}
How do I make the console appear, because it is hard closing the apps from here
Any help would be appreciated :)
Edit:
This is the delay code :
public static void delay(){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I'm using Vaadin and it seems that the Clicklistener of my Button recognizes a click where no click is.
When I load the page in my browser, I get an error message, TreeTaggerException is fired, because the List "selectedWords" is empty.
buildDic = new Button();
buildDic.addClickListener(new ClickListener() {
public void buttonClick(ClickEvent event) {
Dictionary dic1 = new Dictionary();
try {
dic1.generateDictionary("D:/....txt", selectedWords, 5, 5, 6);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TreeTaggerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Where does the event come from, or where is my mistake?
I am trying to set a button to green for 1 second, then back to red. But It won't change to green anymore, if I comment out the "change to red" part, it will turn green fine. I have used Log.d and it shows that there is a second difference between changing from "change to green" to "change to red" so you should see the green before the red, but for some reason this is not working.
Any Ideas?
public void level1() throws InterruptedException {
int Low = 1000;
int High = 3000;
int t = r.nextInt(High-Low) + Low;
Thread.sleep(t);
handleTime.post(new Runnable() {
#Override
public void run() {
int i = r.nextInt(5);
switch(i) {
case 1:
try {
setGreen(tLeft);
tLActive = true;
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
tLActive = false;
setRed(tLeft);
}
break;
case 2:
try {
setGreen(tRight);
tRActive = true;
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
tRActive = false;
setRed(tRight);
}
break;
case 3:
try {
setGreen(center);
cActive = true;
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
cActive = false;
setRed(center);
}
break;
case 4:
try {
setGreen(bLeft);
bLActive = true;
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
bLActive = false;
setRed(bLeft);
}
break;
case 5:
try {
setGreen(bRight);
bRActive = true;
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
bRActive = false;
setRed(bRight);
}
break;
}
}
});
}
private void setGreen(ImageButton b) {
b.setBackgroundResource(R.drawable.green);
Log.d("green", "green");
}
private void setRed(ImageButton b) {
b.setBackgroundResource(R.drawable.red);
Log.d("red", "red");
}
You able to use Handler.class
As simple example:
setGreenColor();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
setRedColor();
}
}, 1000);
where postDelayed will be called in UI thread.
The Runnable in this case runs on the UI thread. The same thread responsible for drawing. But drawing is not immediate instead the UI element gets invalidated because it wants to be redraw and when the UI thread has time it will preform the redraw.
{ //the essence of the runnable code
setGreen(bRight); //UI element is invalidated, it wants to be redrawn green
Thread.sleep(1000); //UI thread is tied up here (blocked) so nothing can happen on UI
setRed(bRight); //UI element is invalidated again, it wants to be redrawn red now
// replacing the green before it's even been seen
} //end of runnable code
//now the redrawing occurs, and it will only be red.
As Eldar Mensutov points out one solution is to post another runnable with a delay. That way the UI thread will not be blocked by the Thread.sleep.
I am attempting to load a saved file from JFileChooser using an actionListener. Here is a snippet of code.
class chooserListener implements ActionListener{
public void actionPerformed (ActionEvent e)
{
if (e.getSource() instanceof JFileChooser){
JFileChooser openFile = (JFileChooser)e.getSource();
String command = e.getActionCommand();
if (command.equals(JFileChooser.APPROVE_SELECTION)){
File selectedFile = openFile.getSelectedFile();
loadSavedGame(selectedFile);
System.out.print("clicked open file");
tp.setSelectedIndex(0);
}
else if (command.equals(JFileChooser.CANCEL_SELECTION)) {
System.out.print("tester");
tp.setSelectedIndex(0);
}
}
}
}
chooser.addActionListener(new chooserListener());
public void loadSavedGame(File loadfile) {
int allCells = countCells(loadfile);
setMineGame(allCells);
try {
Scanner loadFile = new Scanner(loadfile);
while (loadFile.hasNextInt()){
for (int i = 0; i < allCells; i++){
mineGame.setCell(i, loadFile.nextInt());
//System.out.print("loading saved game");
}
loadFile.close();
mineGame.repaint();
tp.setSelectedIndex(0);
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
private int countCells(File countCell) {
int cellCount = 0;
try {
Scanner getCells = new Scanner(countCell);
while (getCells.hasNextInt()){
cellCount++;
}
getCells.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.print(cellCount);
return cellCount;
}
public void setMineGame(int cells) {
game.removeAll();
mineGame.setDifficulty(cells);
mineGame = new Board(statusbar, difficulty);
game.add(mineGame, BorderLayout.CENTER);
game.add(statusbar, BorderLayout.SOUTH);
frame.validate();
frame.repaint();
}
public void setDifficulty(int cells){
if(cells == 256){
difficulty = 0;
}
if (cells == 676){
difficulty = 1;
}
else difficulty = 2;
}
I feel like I have too many methods for the action listener to do. It is hanging when I click 'open', and the test print line 'System.out.print("clicked open file");' does not print. the rest of my code is really large and I'm not sure how to to an SSCE(?). I'm wondering if anyone can see why my actionListener is hanging? thanks IA
It seems like loadSavedGame(File file) takes a lot of time to execute. As this method is running in the Event Dispatch Thread you feel like your program is hanging and never reaches System.out.print("clicked open file"); line. I'd start testing the time of response for this method in a separate test case
Anyway I'd suggest you a few tips:
1) Note there's no need to implement an ActionListener to do your code. You can simple make this:
JFileChooser chooser = new JFileChooser();
int returnValue = chooser.showOpenDialog(null);
if(returnValue == JFileChooser.APPROVE_OPTION){
//make stuff if approved
} else if(returnValue == JFileChooser.CANCEL_OPTION){
//make stuff if canceled
}
I think it makes people life easier.
2) On the other hand note you have two I/O operations: getting the cells count through countCells(File countCell) method and getting the cells themselves inside loadSavedGame(File loadfile) method. You can do it better reading the file just once:
public List<Integer> getCells(File file){
List<Integer> list = new ArrayList<>();
try {
Scanner getCells = new Scanner(file);
while (getCells.hasNextInt()){
list.add(Integer.valueOf(getCells.nextInt()));
}
getCells.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
return list;
}
}
And make this change in loadSavedGame method:
public void loadSavedGame(File loadfile) {
List<Integer> allCells = getCells(loadfile);
setMineGame(allCells.size());
int index = 0;
for(Integer value : allCells){
mineGame.setCell(index, value);
index++;
}
mineGame.repaint();
tp.setSelectedIndex(0);
}
I have JTabbedPane with 4 tabs. JtabbedPane is situated on a JLayeredPane. 1st and 4th tab contain JTable with custom models. Each of the tables is being refreshed every 5-10 seconds.
When 1st tab is active, and JTable on 4th has just finished refreshing, I can see content of the 4th on the 1st. Look at the screenshot.
When I click on the other tab, or minimize window, that strange effect is gone. Till the next refresh of that table on 4th tab. Refreshing is done using Future<> object.
I used Swing GUI builder in Netbeans, so I have huge amount of code. Would post any piece which could be useful.
I tried to revalidate jTabbedPane, is had no effect. Both tables and jScrollPanes has opaque property set to true. So I tried to use SwingUtilities.invokeLater(). It helped a little bit - now first content update goes well, but later - the same problem.
2nd table model has method to update it's content
public void setData(LinkedList<Object[]> __rows) {
NewDevsTableModel.__rows = __rows;
fireTableDataChanged();
}
It is used here (I added SwingUtilities here)
static class checkNew implements Callable<Boolean> {
#Override
public Boolean call() {
ServiceMessage sm = ServiceMessage.getNewList();
try {
connect();
os.write(sm.serialize());
for (int i=0; i<10; i++) {
try {
Thread.sleep(300);
} catch (InterruptedException e) {}
if (is.available() > 0) {
break;
}
if (i == 9) {
disconnect();
return false;
}
}
byte[] actByte = new byte[is.available()];
is.read(actByte);
try {
sm = ServiceMessage.Deserialize(actByte); //may be there are no new devices
if (sm.getType() == ServiceMessageType.NODATA) {
MainWindow.jTabbedPane1.setEnabledAt(3, false);
if (MainWindow.jTabbedPane1.getSelectedIndex() == 3) {
MainWindow.jTabbedPane1.setSelectedIndex(0);
}
return true;
} else {
return false; //wrong answer type
}
} catch (ClassCastException | StreamCorruptedException e) {
//remember selection and scroll
final int scroll = MainWindow.jScrollPane3.getVerticalScrollBar().getValue();
final int[] rows = MainWindow.newDevsTable.getSelectedRows();
int col = MainWindow.devicesTable.getSelectedColumn();
String[] parts = new String(actByte).split("\n");
final LinkedList<Object[]> l = new LinkedList();
for (int i=0; i<parts.length; i++) {
String[] dev = parts[i].split(";", -1);
String descr = dev[2];
boolean iptype = (!dev[3].equals("-"));
String address = dev[4];
boolean atmtype = (dev[5].equals("+"));
if (MainWindow.newDevsTable.getRowCount() >= (i+1)) {
if ((MainWindow.newDevsTable.getValueAt(i, 4) != null) && !MainWindow.newDevsTable.getValueAt(i, 4).equals("")) {
descr = MainWindow.newDevsTable.getValueAt(i, 4).toString();
}
}
Object[] o = {dev[0], dev[1], MainWindow.language[180], MainWindow.language[4], descr, iptype, address, atmtype};
l.add(o);
}
if (!l.isEmpty()) {
SwingUtilities.invokeLater( new Runnable() {
#Override
public void run() {
MainWindow.newDevsPanel.setVisible(true);
MainWindow.jTabbedPane1.setEnabledAt(3, true);
((NewDevsTableModel)MainWindow.newDevsTable.getModel()).setData(l);
ButtonColumn buttonColumn = new ButtonColumn(MainWindow.newDevsTable, addAction, 2, true);
buttonColumn = new ButtonColumn(MainWindow.newDevsTable, rejAction, 3, false);
//put selection back
for (int i=0; i<rows.length; i++) {
MainWindow.newDevsTable.addRowSelectionInterval(rows[i], rows[i]);
}
MainWindow.jScrollPane3.getVerticalScrollBar().setValue(scroll);
}
});
} else {
MainWindow.jTabbedPane1.setEnabledAt(3, false);
if (MainWindow.jTabbedPane1.getSelectedIndex() == 3) {
MainWindow.jTabbedPane1.setSelectedIndex(0);
}
}
return true;
}
} catch (IOException e) {
disconnect();
return false;
} catch (ClassNotFoundException e) {
return false;
}
}
}
I submit the task this way
public static Future<Boolean> checkNewDevices() {
final Future<Boolean> task;
task = service.submit(new checkNew());
return task;
}
To refresh automatically I use separate thread
public class CheckNewPassThread extends Thread {
int pause = 10000;
#Override
public void run() {
for (;;) {
HostConnection.checkNewDevices();
try {
Thread.sleep(pause);
} catch (InterruptedException e) {}
}
}
}
Which is started when the window is opened
private void formWindowOpened(java.awt.event.WindowEvent evt) {
HostConnection.getData();
HostConnection.getDeviceAddress();
RefreshData refreshThread = new RefreshData();
refreshThread.start();
new CheckNewPassThread().start();
}
OMG, the problem was in calling jTabbedPane.setEnabledAt(3, true) to already enabled tab. Swing is fascinating