What I want to do is

1. Take strings from the user and store it in a vector<string>
2. Loop through each string, typing each letter of the string

How would I go about doing this?

Robot r = new Robot();

char letter = 'a';
r.keyPress( (int) letter )

Won't work - since it wants a keycode

The following -almost- works;
It can type out a-z, A-Z, 0-9
but not åäö or !"# etc

How can I fix this/change the code so it can print out everything?

//Set vString_size
  vString_size = vString.size();
		
  //Start typing the given strings
  for( int i=0; i<vString_size; i++ ) //Run through all the strings
     {
      //Set string_size
      string_size = vString.get(i).length();
			
  for( int j=0; j<string_size; j++ ) //Run through each letter
     {
     //Set letter
     letter = vString.get(i).charAt(j);
				
     //Get keycode
     int keycode = KeyEvent.getExtendedKeyCodeForChar(letter);
     
      r.keyPress  ( keycode ); //Press key
 
      r.keyRelease( keycode ); //Release key
				
     }
			
	 //Press [ENTER]
	 r.keyPress( KeyEvent.VK_ENTER );
	 r.keyRelease( KeyEvent.VK_ENTER );
	
           try
	     {
		Thread.sleep(520);
	     }
	   catch(Exception exec)
		{
		exec.printStackTrace();
		}
	  }

So, basically, what you want to do is print out a string to the screen character by character?

The simplest way to do so is to use a for loop and after every string, use the wait() function...

Thread.getCurrentThread().wait(1000);
//Makes the program wait for 1000 milliseconds, i.e. 1 second!

Hope this helps :)

[EDIT: Isn't your way a little too complicated? I mean, it's fine, but the direct method works fine :)]

commented: no, that is not what he's trying to do. -3

So, basically, what you want to do is print out a string to the screen character by character?

The simplest way to do so is to use a for loop and after every string, use the wait() function...

Thread.getCurrentThread().wait(1000);
//Makes the program wait for 1000 milliseconds, i.e. 1 second!

Hope this helps :)

[EDIT: Isn't your way a little too complicated? I mean, it's fine, but the direct method works fine :)]

No, I don't want to just print out a string to the console, I want to simulate key presses.

Can you explain a bit more? You want the event for key presses to be fired? Be a little more specific.

I think you may want to take a look at the KeyListener and KeyEvent classes.

Can you explain a bit more? You want the event for key presses to be fired? Be a little more specific.

...
I want the program to type the strings with
Robot r = new Robot();
r.keyPress( keyCode );
r.keyRelease( KeyCode );

...
I want the program to type the strings with
Robot r = new Robot();
r.keyPress( keyCode );
r.keyRelease( KeyCode );

The code looks like you're trying to fire an event.
Just have a look at this
Key Press ---> Event Fired ---> Something happens

You are trying to get the key pressed like this
Event Fired ---> Something happens

Jumping to the second step won't make the first step happen. Get my drift?

The code looks like you're trying to fire an event.
Just have a look at this
Key Press ---> Event Fired ---> Something happens

You are trying to get the key pressed like this
Event Fired ---> Something happens

Jumping to the second step won't make the first step happen. Get my drift?

My problem isn't that it isn't working at all though
a-z, A-Z and 0-9 works fine.
It's å, ä, ö and !"# etc that doesn't work

There may be some problem with the encoding... Just check the documentation once

There may be some problem with the encoding... Just check the documentation once

Hm, I just found the following at
http://docs.oracle.com/javase/1.4.2/docs/api/java/awt/event/KeyEvent.html


"Not all characters have a keycode associated with them. For example, there is no keycode for the question mark because there is no keyboard for which it appears on the primary layer."

, and . works fine, but ! ? # and the rest do not..


There has to be some workaround or a complete other way of doing what I want to do, though?
:/

primary layer

These two words are of importance. Google for "accessing keys of the second layer using java"

Maybe the problem is the Robot is pressing keys at the "hardware" level, not at the logical character level. So for upper-case A you need to press VK_SHIFT then VK_A, then release them both
On my UK keyboard ! is VK_SHIFT then VK_1, etc. But the code sequence for accented chars etc are completely different between my UK and French keyboards. The API JavaDoc for KeyEvent explains further.
Before you ask... no I don't know how get a map of chars to VK combinations for the currently installed keyboard layout - if you find out please post the answer here!

Robot must waiting for (half)second before first usage, this downvote isn't correct

screen capture is same as SendKey by default

import javax.imageio.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;

public class CaptureScreen implements ActionListener {

    private JFrame f = new JFrame("Screen Capture");
    private JPanel pane = new JPanel();
    private JButton capture = new JButton("Capture");
    private JDialog d = new JDialog();
    private JScrollPane scrollPane = new JScrollPane();
    private JLabel l = new JLabel();
    private Point location;
    private Timer timer1;

    public CaptureScreen() {
        capture.setActionCommand("CaptureScreen");
        capture.setFocusPainted(false);
        capture.addActionListener(this);
        capture.setPreferredSize(new Dimension(300, 50));
        pane.add(capture);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(pane);
        f.setLocation(100, 100);
        f.pack();
        f.setVisible(true);
        createPicContainer();
        startTimer();
    }

    private void createPicContainer() {
        l.setPreferredSize(new Dimension(700, 500));
        scrollPane = new JScrollPane(l,
                ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
                ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        scrollPane.setBackground(Color.white);
        scrollPane.getViewport().setBackground(Color.white);
        d.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
        d.add(scrollPane);
        d.pack();
        d.setVisible(false);
        d.addWindowListener(new WindowListener() {

            public void windowOpened(WindowEvent e) {
            }

            public void windowClosing(WindowEvent e) {
                f.setVisible(true);
            }

            public void windowClosed(WindowEvent e) {
            }

            public void windowIconified(WindowEvent e) {
            }

            public void windowDeiconified(WindowEvent e) {
            }

            public void windowActivated(WindowEvent e) {
            }

            public void windowDeactivated(WindowEvent e) {
            }
        });
    }

    private void startTimer() {
        timer1 = new Timer(1000, new AbstractAction() {

            private static final long serialVersionUID = 1L;

            @Override
            public void actionPerformed(ActionEvent e) {
                SwingUtilities.invokeLater(new Runnable() {

                    @Override
                    public void run() {
                        capture.doClick();
                        f.setVisible(false);
                    }
                });
            }
        });
        timer1.setDelay(500);
        timer1.setRepeats(false);
        timer1.start();
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getActionCommand().equals("CaptureScreen")) {
            Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); // gets the screen size
            Robot r;
            BufferedImage bI;
            try {
                r = new Robot(); // creates robot not sure exactly how it works
                Thread.sleep(1000); // waits 1 second before capture
                bI = r.createScreenCapture(new Rectangle(dim)); // tells robot to capture the screen
                showPic(bI);
                saveImage(bI);
            } catch (AWTException e1) {
                e1.printStackTrace();
            } catch (InterruptedException e2) {
                e2.printStackTrace();
            }
        }
    }

    private void saveImage(BufferedImage bI) {
        try {
            ImageIO.write(bI, "JPG", new File("screenShot.jpg"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void showPic(BufferedImage bI) {
        ImageIcon pic = new ImageIcon(bI);
        l.setIcon(pic);
        l.revalidate();
        l.repaint();
        d.setVisible(false);
        //location = f.getLocationOnScreen();
        //int x = location.x;
        //int y = location.y;
        //d.setLocation(x, y + f.getHeight());
        d.setLocation(150, 150);
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                d.setVisible(true);
            }
        });
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                CaptureScreen cs = new CaptureScreen();
            }
        });
    }
}

These two words are of importance. Google for "accessing keys of the second layer using java"

Couldn't find anything ;(

Robot must waiting for (half)second before first usage, this downvote isn't correct

It has to wait half a second?
Well that isn't really a problem here since the user has to type in strings.

What do you mean by "this downvote isn't correct"?

Also, not sure how the code you posted can help me.

The wait is useful before a Robot screen capture to allow the OS to finish refreshing aall the other windows etc on the screen after your Java app is loaded. I don't think you need it before pressKey.

ps did you try pressing VK_SHIFT the VK_1 then releasing them?

@sha11e

Also, not sure how the code you posted can help me.

I'm talking about reason and downvoting,

@JamesCherrill

this AWT bridge is very strange and designeted for Win95/NT/2000, really don't know reason why this API exists there until today

in other hand works (most cases) as you described in your last post

I'm talking about reason and downvoting,

if you are referring to my downvote, that was not about implementing the delay.

Your code was working save for some characters, right?

[edit: forget the quote. I just clicked reply :)]

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.