Friday, 25 October 2013

Java Robot class simulating human mouse movement

Take a look in this example that I wrote. You can improve this to simulate what Joey said. I wrote it very fast and there are lots of things that can be improved (algorithm and class design). Note that I only deal with left to right movements.

import java.awt.AWTException;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.Robot;

public class MouseMoving {

    public static void main(String[] args) {
        new MouseMoving().execute();
    }

    public void execute() {
        new Thread( new MouseMoveThread( 100, 50, 50, 10 ) ).start();
    }

    private class MouseMoveThread implements Runnable {

        private Robot robot;
        private int startX;
        private int startY;
        private int currentX;
        private int currentY;
        private int xAmount;
        private int yAmount;
        private int xAmountPerIteration;
        private int yAmountPerIteration;
        private int numberOfIterations;
        private long timeToSleep;

        public MouseMoveThread( int xAmount, int yAmount,
                int numberOfIterations, long timeToSleep ) {

            this.xAmount = xAmount;
            this.yAmount = yAmount;
            this.numberOfIterations = numberOfIterations;
            this.timeToSleep = timeToSleep;

            try {

                robot = new Robot();

                Point startLocation = MouseInfo.getPointerInfo().getLocation();
                startX = startLocation.x;
                startY = startLocation.y;

            } catch ( AWTException exc ) {
                exc.printStackTrace();
            }

        }

        @Override
        public void run() {

            currentX = startX;
            currentY = startY;

            xAmountPerIteration = xAmount / numberOfIterations;
            yAmountPerIteration = yAmount / numberOfIterations;

            while ( currentX < startX + xAmount &&
                    currentY < startY + yAmount ) {

                currentX += xAmountPerIteration;
                currentY += yAmountPerIteration;

                robot.mouseMove( currentX, currentY );

                try {
                    Thread.sleep( timeToSleep );
                } catch ( InterruptedException exc ) {
                    exc.printStackTrace();
                }

            }

        }

    }

}

Monday, 21 October 2013

Showing only close button on the JFrame undecorated


public class TestUndecoratedFrame {

    public static void main(String[] args) {
        new TestUndecoratedFrame();
    }

    public TestUndecoratedFrame() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                TitlePane titlePane = new TitlePane();

                JFrame frame = new JFrame("Testing");
                frame.setUndecorated(true);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                ((JComponent)frame.getContentPane()).setBorder(new LineBorder(Color.BLACK));
                frame.add(titlePane, BorderLayout.NORTH);
                frame.add(new JLabel("This is your content", JLabel.CENTER));
                frame.setSize(200, 200);
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TitlePane extends JPanel {

        public TitlePane() {
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.weightx = 1;
            gbc.anchor = GridBagConstraints.EAST;
            add(new CloseControl(), gbc);
        }
    }

    public class CloseControl extends JButton {

        public CloseControl() {
            setBorderPainted(false);
            setContentAreaFilled(false);
            setFocusPainted(false);
            setOpaque(false);
            setBorder(new EmptyBorder(0, 0, 8, 12));
            try {
                setRolloverIcon(new ImageIcon(ImageIO.read(getClass().getResource("/Highlighted.png"))));
                setRolloverEnabled(true);
                setIcon(new ImageIcon(ImageIO.read(getClass().getResource("/Normal.png"))));
            } catch (IOException ex) {
                Logger.getLogger(TestUndecoratedFrame.class.getName()).log(Level.SEVERE, null, ex);
            }

            addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    SwingUtilities.getWindowAncestor(CloseControl.this).dispose();
                }
            });
        }
    }
}

Wednesday, 16 October 2013

jQuery check if element is visible or hidden

Useful jQuery toggle visibility methods.

Or you may check if element is visible or hidden with jQuery. Hide or show it according to its visibility.
Test code:
html:
<div class="wrap-js-action"><span class="click js-action">click to show or hide (display:block|none;)</span></div>
<div class="target">target</div>
 
<div class="wrap-js-action"><span class="click-toggle js-action">click to show or hide by toggle (display:block|none;)</span></div>
<div class="target-toggle">target-toggle</div>
 
<div class="wrap-js-action"><span class="click-visibility js-action">click to show or hide (visibility:hidden|visible)</span></div>
<div class="target-visibility">target visibility</div>
 
<div class="wrap-js-action"><span class="click-opacity js-action">click to show or hide (opacity:0|1)</span></div>
<div class="target-opacity">target opacity</div>
 
<div>last line</div>
jQuery:
$('.click').click(function() {
    if ($('.target').is(':hidden')) {
        $('.target').show();
    } else {
        $('.target').hide();
    }
});
 
 
$('.click-toggle').click(function() {
    $('.target-toggle').toggle();
});
 
$('.click-visibility').click(function() {
    if ($('.target-visibility').css('visibility') == 'hidden'){
        $('.target-visibility').css({'visibility': 'visible', display: ''});
    }else{
        $('.target-visibility').css({'visibility': 'hidden', display: ''});
    }
});
 
$('.click-opacity').click(function() {
    if ($('.target-opacity').css('opacity') == '0'){
        $('.target-opacity').css({'opacity': '1', display: ''});
    }else{
        $('.target-opacity').css({'opacity': '0', display: ''});
    }
});
​​
.js-action {
    cursor: pointer;
    border-bottom:1px dashed #555;
}

.wrap-js-action {
    margin:15px 0 0 0;
}
Difference between "display:none", "visibility:hidden" and "opacity:0":
  • display:none hides the element and it does not take up any space;
  • visibility:hidden hides the element, but it still takes up space in the layout;
  • opacity:0 hides the element as "visibility:hidden" and it still takes up space in the layout; the only difference is that opacity let to do element partly transparent;
Another difference between visibility:hidden and opacity:0 is that the element will still respond to events (like clicks) with opacity:0.

Friday, 4 October 2013

Using Callable to Return Results From Runnables

The Runnable interface has been around since the beginning of time for the Java platform. It allows you to define a task to be completed by a thread. As most people probably know already, it offers a single method run() that accepts no arguments and returns no values, nor can it throw any checked exceptions. If you need to get a value back from the now-completed task, you must use a method outside the interface and wait for some kind of notification message that the task completed. For example, the following demonstrates what you might do for just such a scenario:
  Runnable runnable = ...;
  Thread t = new Thread(runnable);
  t.start();
  t.join();
  String value = someMethodtoGetSavedValue()
Nothing is inherently wrong with this code, but it can be done differently now, thanks to the Callable interface introduced in J2SE 5.0. Instead of having a run() method, the Callable interface offers a call() method, which can return an Object or, more specifically, any type that is introduced in the genericized form:
  public interface Callable<V> {
     V call() throws Exception;
  }
Because you cannot pass a Callable into a Thread to execute, you instead use the ExecutorService to execute the Callable object. The service accepts Callable objects to run by way of the submit() method:
  <T> Future<T> submit(Callable<T> task)
As the method definition shows, submitting a Callable object to the ExecutorService returns a Future object. Theget() method of Future will then block until the task is completed. This is the equivalent of the join() call in the first example. Actually, it is the equivalent of both the join() call and the get value call as get() returns the value calculated by the Callable instance.
To demonstrate, the following example creates separate Callable instances for each word passed in on the command line and sums up their length. Each Callable will just calculate the sum of its individual word. The set ofFuture objects are saved to acquire the calculated value from each. If the order of the returned values needed to be preserved, a List could be used instead.
import java.util.\*;
import java.util.concurrent.\*;

public class CallableExample {

  public static class WordLengthCallable
        implements Callable {
    private String word;
    public WordLengthCallable(String word) {
      this.word = word;
    }
    public Integer call() {
      return Integer.valueOf(word.length());
    }
  }

  public static void main(String args[]) throws Exception {
    ExecutorService pool = Executors.newFixedThreadPool(3);
    Set<Future<Integer>> set = new HashSet<Future≶Integer>>();
    for (String word: args) {
      Callable<Integer> callable = new WordLengthCallable(word);
      Future<Integer> future = pool.submit(callable);
      set.add(future);
    }
    int sum = 0;
    for (Future<Integer> future : set) {
      sum += future.get();
    }
    System.out.printf("The sum of lengths is %s%n", sum);
    System.exit(sum);
  }
}
The WordLengthCallable saves each word and uses the word's length as the value returned by the call()method. This value could take some time to generate but in this case is known immediately. The only requirement ofcall() is the value is returned at the end of the call. When the get() method of Future is later called, the Futurewill either have the value immediately if the task runs quickly, as in this case, or will wait until the value is done generating. Multiple calls to get() will not cause the task to be rerun in the thread.
Because the goal of the program is to calculate the sum of all word lengths, it doesn't matter in which order theCallable tasks finish. It is perfectly OK if the last task completes before the first three. The first get() call to Futurewill just wait for the first task in the Set to complete. This does not block other tasks from running to completion separately. It is just waiting for that one thread or task to complete.