I am trying to copy words from anywhere (like MS word, pdf, not from any java component) to clip board when I double click on it. Therefore, I use awt.Robot to copy that selected word to clip board after double click on it. After copy, the word will return. Therefore, I use two method copy_From_Original and copy_From_ClipBoard.
The problem is when I copy word, it will show the previous word that clipboard content not the current copied one.
If there are, another ways to do this process feel free to say it.
Thanks. Sorry for my bad English.
public class copyWord {
public static String copy_From_Original() {
try {
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_C);
robot.keyRelease(KeyEvent.VK_C);
robot.keyRelease(KeyEvent.VK_CONTROL);
} catch (AWTException ex) {
Logger.getLogger(copyWord.class.getName()).log(Level.SEVERE, null, ex);
}
String word = copy_From_ClipBoard();
return word;
}
private static String copy_From_ClipBoard() {
Toolkit toolkit = Toolkit.getDefaultToolkit();
Clipboard clipboard = toolkit.getSystemClipboard();
try {
String result = (String) clipboard.getData(DataFlavor.stringFlavor);
return result;
} catch (Exception e) {
System.out.println("ERROR");
return null;
}
} }
Do not use Robot for this. You haven’t said what type of component contains the double-clicked text, but if it’s a JTextField or JTextArea or any other subclass of JTextComponent, you can simply call copy().
If it’s an AWT TextField or TextArea, you can use place the selection on the clipboard yourself:
String text = textField.getSelectedText();
Clipboard clipboard = textField.getToolkit().getSystemClipboard();
clipboard.setContents(new StringSelection(text), null);
Related
I am new to Java
I created a conversion software for metric units and now I want to create new window for logging the output of converted units from one Window text areas into one text area in another window Picture of the application
Both Windows are one application
What code would I need to put in there to display this in another window text area
JButton btnConvert = new JButton("Convert");
btnConvert.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
double numCM,sumCM;
double numKM,sumKM;
double numMIL,sumMIL;
try {
//startCM//
numCM = Double.parseDouble(textFieldenter.getText());
sumCM = numCM*100;
textFieldcm.setText(Double.toString(sumCM));
//endCM//
//startKILOMETERS//
numKM = Double.parseDouble(textFieldenter.getText());
sumKM = numKM*0.001;
textFieldkm.setText(Double.toString(sumKM));
//endKILOMETERS//
//startMILES//
numMIL = Double.parseDouble(textFieldenter.getText());
sumMIL = numMIL*0.000621;
textFieldmil.setText(Double.toString(sumMIL));
//endMILES//
}
catch (Exception e1) {
JOptionPane.showInternalMessageDialog(btnConvert, "Value etered is incorrect");
}
}
});
You can use the method JTextField.getText() over your JTextFields and store its value into a String variable, then pass it to the JTextArea using the method append(String str) and put a line break at the end with /n
Read the API for these classes to learn more about its methods and how to use them Java API
It would be something like this
String record = "";
record = textFieldcm.getText()+" "+textFieldkm.getText()+" "+textFieldmil.getText();
JTextArea.append(record+"\n");
I'm trying to programmatically add some text to the system clipboard, paste it to a random application from there and restore the clipboard to the state it was before, but Java seems to have a problem with that.
Out of ten tries it never pastes the text more than eight times and sometimes even the wrong text (the text that was in the clipboard before) is pasted.
Any help would be greatly appreciated!
public class ClipboardTestClass {
static Robot robot;
public static void main(String[] args) {
try {
robot = new Robot();
} catch (AWTException ex) {
Logger.getLogger(TestApp.class.getName()).log(Level.SEVERE, null, ex);
}
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
Logger.getLogger(TestApp.class.getName()).log(Level.SEVERE, null, ex);
}
for(int i = 0; i< 10; i++){
enterString("Hello\n");
}
}
public static void enterString(String myString){
System.out.println("Trying to paste string \"" + myString + "\"");
StringSelection stringSelection = new StringSelection(myString);
//save clipboard content
Transferable clipboardContent = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
//enter new clipboard content
Toolkit.getDefaultToolkit().getSystemClipboard().setContents((Transferable) stringSelection, null);
//paste clipboard content with Robot class
robot.keyPress(VK_CONTROL);
robot.keyPress(VK_V);
robot.keyRelease(VK_CONTROL);
robot.keyRelease(VK_V);
//restore clipboard content
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(clipboardContent, null);
}
}
This will never work reliably. You would have to handle all formats, no matter what the size. Read up on Delayed Rendering (where the data doesn't actually exist on the clipboard at all until a request is made to paste it), and you will start to understand the problem. Some apps, like Excel, can provide the data in 25+ formats, some of them very large and complex. There isn't time or RAM to render them all.
So you can't restore the clipboard the way it was.
And you can't update the clipboard at all, without triggering other clipboard-aware apps from doing "their thing".
And lastly, you should not be using the clipboard this way. The clipboard is a shared resource, provided for the convenience of the USER, not the programmer.
Find another way.
For String type content (ONLY!!!), I came up with this snippet:
import static java.awt.Toolkit.getDefaultToolkit;
public class Main {
public static void main(String[] args) throws IOException, UnsupportedFlavorException {
Clipboard systemClipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
// Save the old data
String oldData = (String) systemClipboard.getContents(null).getTransferData(DataFlavor.stringFlavor);
// Now lets put some new data to clipboard!
StringSelection stringSelection = new StringSelection("Jai Hind!! Vandee Maatharam!!!!");
systemClipboard.setContents(stringSelection, null);
// Lets print the clipboard content
String newData = (String)
systemClipboard.getContents(null).getTransferData(DataFlavor.stringFlavor);
System.out.println("Here is the new data: [" + newData + "]");
// Now setting back the old clipboard content
StringSelection oldDataSelection = new StringSelection(oldData);
systemClipboard.setContents(oldDataSelection, null);
//Now hit CTRL+V in an editor and you should get back the old clipboard content (NOTE: Only String Contents!!!)
}
I have a JEditorPane and I put a mouse listener on it and can detect where the cursor is.
However, I would like to be able to get the text of the line where my cursor is. Is there a utility method I can use? If not, then how would I construct a method to do this?
xmlEditor.addMouseListener(
new MouseAdapter() {
public void mouseClicked(MouseEvent me) {
try {
int caretPosition = xmlEditor.getCaretPosition();
int offset = 0;
int length = 0;
xmlEditor.getText(offset, length);
} catch (BadLocationException ex) {
Logger.getLogger(EZXPathFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
);
Is there a utility method I can use?
Never tried it with a JEditorPane but you might be able to use the Utilities class. You should be able to use methods like getRowStart(...) and getRowEnd(...). Once you know the starting and ending offset you can get the text from the JEditorPane.
Something like:
int start = Utilities.getRowStart(textComponent, offset);
int end = Utilities.getRowEnd(textComponent, offset);
String text = textComponent.getText(start, end-start);
I already know how to use java.awt.Robot to type a single character using keyPress, as seen below. How can I simply enter a whole pre-defined String value at once into a textbox?
robot.keyPress(KeyEvent.VK_1);
robot.keyPress(KeyEvent.VK_1);
robot.keyPress(KeyEvent.VK_1);
// instead, enter String x = "111"
Common solution is to use the clipboard:
String text = "Hello World";
StringSelection stringSelection = new StringSelection(text);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, stringSelection);
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
Since Java 7 you can also use KeyEvent.getExtendedKeyCodeForChar(c). An example for lower case only could be:
void sendKeys(Robot robot, String keys) {
for (char c : keys.toCharArray()) {
int keyCode = KeyEvent.getExtendedKeyCodeForChar(c);
if (KeyEvent.CHAR_UNDEFINED == keyCode) {
throw new RuntimeException(
"Key code not found for character '" + c + "'");
}
robot.keyPress(keyCode);
robot.delay(100);
robot.keyRelease(keyCode);
robot.delay(100);
}
}
You need to "type" the character, which is a press AND release action...
robot.keyPress(KeyEvent.VK_1);
robot.keyRelease(KeyEvent.VK_1);
Now you could just copy and paste it three times, but I'd just put it in a loop
You can enter value in a string and then you can use that string as explained by Eng.Fouad. But there is no fun in using it, you can give a try to this
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_H);
robot.keyRelease(KeyEvent.VK_H);
robot.keyPress(KeyEvent.VK_E);
robot.keyRelease(KeyEvent.VK_E);
robot.keyPress(KeyEvent.VK_L);
robot.keyRelease(KeyEvent.VK_L);
robot.keyPress(KeyEvent.VK_L);
robot.keyRelease(KeyEvent.VK_L);
robot.keyPress(KeyEvent.VK_O);
robot.keyRelease(KeyEvent.VK_O);
and you can also use Thread.sleep so that it can enter data bit slowly.
This doesn't type the entire "string" but helps to type whatever you want other than one character at a time.
Runtime.getRuntime().exec("notepad.exe");//or anywhere you want.
Thread.sleep(5000);//not required though gives a good feel.
Robot r=new Robot();
String a="Hi My name is Whatever you want to say.";
char c;
int d=a.length(),e=0,f=0;
while(e<=d)
{
c=a.charAt(e);
f=(int) c; //converts character to Unicode.
r.keyPress(KeyEvent.getExtendedKeyCodeForChar(f));
e++;
Thread.sleep(150);
}
see it works perfectly and it's awesome!
Though it doesn't work for special characters which cannot be traced by unicode like |,!...etc.
I think I've implemented better soultion, maybe someone found it usefull (the main approach is to read all values from enum KeyCode and than to put it into a HashMap and use it later to find a int key code)
public class KeysMapper {
private static HashMap<Character, Integer> charMap = new HashMap<Character, Integer>();
static {
for (KeyCode keyCode : KeyCode.values()) {
if (keyCode.impl_getCode() >= 65 && keyCode.impl_getCode() <= 90){
charMap.put(keyCode.getName().toLowerCase().toCharArray()[0], keyCode.impl_getCode());
}
else{
charMap.put(keyCode.getName().toLowerCase().toCharArray()[0], keyCode.impl_getCode());
}
}
}
public static Key charToKey(char c){
if(c>=65 && c<=90){
return new Key(charMap.get(c), true);
} else {
return new Key(charMap.get(c), false);
}
}
public static List<Key> stringToKeys(String text){
List<Key> keys = new ArrayList<Key>();
for (char c : text.toCharArray()) {
keys.add(charToKey(c));
}
return keys;
}
I created also a key class to know whether to type an uppercase or lowercase char:
public class Key {
int keyCode;
boolean uppercase;
//getters setter constructors}
and finally you can use it like that (for single character) robot.keyPress(charToKey('a').getKeyCode());
If you want to press an uppercase you have to press and release with shift key simultaneously
StringSelection path = new StringSelection("path of your document ");
// create an object to desktop
Toolkit tol = Toolkit.getDefaultToolkit();
// get control of mouse cursor
Clipboard c = tol.getSystemClipboard();
// copy the path into mouse
c.setContents(path, null);
// create a object of robot class
Robot r = new Robot();
r.keyPress(KeyEvent.VK_CONTROL);
r.keyPress(KeyEvent.VK_V);
r.keyRelease(KeyEvent.VK_CONTROL);
r.keyRelease(KeyEvent.VK_V);
r.keyPress(KeyEvent.VK_ENTER);
r.keyRelease(KeyEvent.VK_ENTER);
}
I'ved searched some time but no satisfying result showed thus would like to ask here.
Basicallly I have a JAVA Swing GUI table, it has some rows, let's say 3 columns each row, you see "1 david good" on a row. the content of this row is converted from a raw message, i.e. a xml message.
What I want to do is, when I selected a row and press ctrl+c, the a raw msg could be copied to clipboard then I could paste it in other Windows application like notepad or Word.
I tried toolkit to get system clipboard and put raw message in(via keylistener). But when I press ctrl+v in notepad, I still get "1 david good" as default.
I printed the raw message from clipboard in Swing code, thus I am guessing if my code only works in Swing, customized content could not be retrieved in Windows?
Could somebody tell me if it's possible to do in Swing? thanks a lot.
You can use this example:
String str = "Which String to copy to clipboard";
StringSelection stringSelection = new StringSelection (str);
Clipboard clpbrd = Toolkit.getDefaultToolkit().getSystemClipboard ();
clpbrd.setContents (stringSelection, null);
So this code can be when clicking on some button while calling it from actionPerformed()
And for pasting issue:
public String getClipboardContents() {
String result = "";
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
//odd: the Object param of getContents is not currently used
Transferable contents = clipboard.getContents(null);
boolean hasTransferableText =
(contents != null) &&
contents.isDataFlavorSupported(DataFlavor.stringFlavor)
;
if (hasTransferableText) {
try {
result = (String)contents.getTransferData(DataFlavor.stringFlavor);
}
catch (UnsupportedFlavorException | IOException ex){
System.out.println(ex);
ex.printStackTrace();
}
}
return result;
}