Problem description : user press print screen button and then click on paste button on application. That image will be store on server.
I googled and find answer on Stack over and used following code
public Image getImageFromClipboard()
{
Clipboard systemClipboard = (Clipboard) AccessController.doPrivileged(new PrivilegedAction() {
public Object run()
{
Clipboard tempClipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
return tempClipboard;
}
});
// get the contents on the clipboard in a
// Transferable object
Transferable clipboardContents = systemClipboard.getContents(null);
// check if contents are empty, if so, return null
if (clipboardContents == null)
return null;
else
try
{
// make sure content on clipboard is
// falls under a format supported by the
// imageFlavor Flavor
if (clipboardContents.isDataFlavorSupported(DataFlavor.imageFlavor))
{
// convert the Transferable object
// to an Image object
Image image = (Image) clipboardContents.getTransferData(DataFlavor.imageFlavor);
return image;
}
} catch (UnsupportedFlavorException ufe)
{
ufe.printStackTrace();
} catch (IOException ioe)
{
ioe.printStackTrace();
}
/*try {
Robot robot;
robot = new Robot();
final GraphicsConfiguration config
= GraphicsEnvironment.getLocalGraphicsEnvironment()
.getDefaultScreenDevice().getDefaultConfiguration();
final BufferedImage screenshot = robot.createScreenCapture(config.getBounds());
return screenshot;
} catch (AWTException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
return null;
}
This code work well if application is running on my machine and I press Print Screen. Image is available and store.
My problem is that when I am deploying this application on separate server and run application on another machine. When user press Print screen and then click on button in application. Server won't find any image because it look on clipboard and on server clipboard no image is available. Image is available on Client desktop clipboard.
Kindly help me to access Client clipboard from server using JSF/primefaces. Or other alternative way.
I am using primefaces 3.4, server is weblogic 10.3.5.
If your application will be running on different browsers, you will find no 100% reliable way of doing it unless you implement some specific component with some other technology like Flash.
I would really use the approach of saving the image and uploading it to the server via a normal file upload form. Else you will be having headaches with Browser security issues.
Regards
Related
My purpose is post with a Featured Image.
This program can post Featured Image.
But dialog doesn't close!
So I can't publish.
public void uploadThumbnail(String imgPath) {
//parent current window
String currentWindow = driver.getWindowHandle();
System.out.println(imgPath);
try {
driver.findElement(By.id("set-post-thumbnail")).click();
sleep(2000);
click(By.linkText("Upload Files"));
//Select Files
sleep(1000);
driver.findElement(By.id("__wp-uploader-id-1")).click();
//upload
driver.findElement(By.xpath("//div[7]/input")).sendKeys(imgPath);
sleep(2000);
driver.findElement(By.xpath("//div[#id='__wp-uploader-id-0']/div[5]/div/div[2]/button")).click();
} catch (Exception e) {
e.printStackTrace();
uploadThumbnail(imgPath);
}
sleep(1000);
}
How to close the dialog or how to ignore the dialog and publish?
I stacked on the page.Finally I find plugin which is "Nelio External Featured Image".
it is can set picture by URL.So I don't need upload window and dialog.
Now I can set a picture on Featured Image on WordPress by Selenium from java!!!
Thank you Nelio External Featured Image developers!!
I need your help please: I'm working on a little Java application (Java version 7) which has to be minimized into the system tray.
I'm using Class SystemTray, with SystemTray.isSupported(), then
SystemTray systemTray = SystemTray.getSystemTray();
ImageIcon icon = new javax.swing.ImageIcon(getClass().getResource("icon.png"));
[...]
systemTray.add(trayIcon);
(With popup of course)
On Windows, it's working great. On XFCE, Xubuntu, no problem, icon is working with popup. However on KDE and Gnome shell... it doesn't work.
KDE (4.14.1)
(Qt: 4.8.6 Tools Plasma: 4.11.12)
SystemTray.isSupported() = true and when the program arrived at the line:
systemTray.add(trayIcon); An exception is caught:
Error during Tray process:
java.awt.AWTException: TrayIcon couldn't be displayed.
Thereby the icon is white, and doesn't work when user clicks on it, no popup.
Gnome Shell (3.12.2)
SystemTray.isSupported() = true, the icon is located on notification area at the bottom, but mouse events don't work...
To fix these problem, I thought SWT could be a good idea. But when I implemented it (last version), I've got this warning:
WARNING **: Couldn't connect to accessibility bus: Failed to connect
to socket /tmp/[...]
And it doesn't work...
Edit: not anymore, I can fix the problem of SWT with an external class. The warning is not caused by SWT, but environment system probably (I had the same warning with other applications in the terminal).
So now, what can I do?
I think to check environment system with System.getenv("XDG_CURRENT_DESKTOP") & System.getenv("GDMSESSION") and then enable or disable system tray if it is KDE or Gnome 3... but this solution is not really good because of it is a local solution for multi-platform (in function of OS I mean), and not a global solution (one method for all OS)...
So, other idea? I don't know... is there a way to define an embedded JWindow into the system tray?
I have run up against this problem myself, and as I recall I ran up against a brick wall in sorting it out with a legitimate solution. I traced the problem to a call to the TrayIcon.addNotify() method randomly failing. I seem to recall this was because of a race condition in the internals where a call to the X11 system was taking too long to complete so the java side was giving up.
But if you have a ninja PC with a decent graphics card you would probably never meet this situation, which is probably why it hasn't been fixed yet. My dev machine is on the slow side so it was happening to me about 50% of the time.
I did hack a quick and dirty solution together, which involves trying to call addNotify repeatedly (with a pause inbetween each attempt) until it succeeds (or has failed a maximum number of times). Unfortunately the only way to do this was via reflection as the addNotify method is package-private.
Code follows:
public class HackyLinuxTrayIconInitialiser extends SwingWorker<Void, TrayIcon> {
private static final int MAX_ADD_ATTEMPTS = 4;
private static final long ADD_ICON_DELAY = 200;
private static final long ADD_FAILED_DELAY = 1000;
private TrayIcon[] icons;
public HackyLinuxTrayIconInitialiser(TrayIcon... ic) {
icons = ic;
}
#Override
protected Void doInBackground() {
try {
Method addNotify = TrayIcon.class.getDeclaredMethod("addNotify", (Class<?>[]) null);
addNotify.setAccessible(true);
for (TrayIcon icon : icons) {
for (int attempt = 1; attempt < MAX_ADD_ATTEMPTS; attempt++) {
try {
addNotify.invoke(icon, (Object[]) null);
publish(icon);
pause(ADD_ICON_DELAY);
break;
} catch (NullPointerException | IllegalAccessException | IllegalArgumentException e) {
System.err.println("Failed to add icon. Giving up.");
e.printStackTrace();
break;
} catch (InvocationTargetException e) {
System.err.println("Failed to add icon, attempt " + attempt);
pause(ADD_FAILED_DELAY);
}
}
}
} catch (NoSuchMethodException | SecurityException | NoSuchFieldException e1) {
Log.err(e1);
}
return null;
}
private void pause(long delay) {
try {
Thread.sleep(delay);
} catch (InterruptedException e1) {
Log.err(e1);
}
}
#Override
protected void process(List<TrayIcon> icons) {
for (TrayIcon icon : icons) {
try {
tray.add(icon);
} catch (AWTException e) {
Log.err(e);
}
}
}
}
To use it, just call:
if (<OS is Linux>) {
new HackyLinuxTrayIconInitialiser(ticon, micon, licon).execute();
} else {
try {
tray.add(ticon);
tray.add(micon);
tray.add(licon);
} catch (AWTException e) {
Log.err(e);
}
}
I seem to recall at the time I couldn't just keep calling SystemTray.add(icon) as it this would leave "ghost" trayicons behind on the system tray if I did.
Hope this helps.
I'm trying to create a button in game where the background color will go from light_gray to dark_gray. However when the application relaunches I have to re select the button to get the color back to dark_gray.
How would I have it so that it saves the color when the application is relaunched?
My code is very simple and is just an action listener on the button which then changes the bg color of selected items.
Ok, I have now had the chance to allow it to create the properties file but one doesn't know how one could store the data. I've seen people have stuff such as 'properties.setProperty("Favorite sport", "Football");'
But how could one have this so that it stores the bg color?
windowDark.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae)
{
try {
Properties properties = new Properties();
properties.setProperty();
File file = new File("DarkTheme.properties");
FileOutputStream fileOut = new FileOutputStream(file);
properties.store(fileOut, "Dark theme background colour");
fileOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
The java.util.prefs Preferences API is well suited for storing persistent preference data for user applications running on the desktop.
Here's an example how you can use it to store and retrieve persistent background color settings:
import java.awt.Color;
import java.util.prefs.Preferences;
public class MyPrefs {
private static Preferences preferences =
Preferences.userRoot().node("myappname.ColorPreferences");
public static void storeBackground(Color background) {
preferences.putInt("background", background.getRGB());
}
public static Color retrieveBackground() {
// Second argument is the default when the setting has not been stored yet
int color = preferences.getInt("background", Color.WHITE.getRGB());
return new Color(color);
}
}
To call it, use something like:
public static void main(String[] args) {
System.out.println("Background: " + retrieveBackground());
storeBackground(Color.RED);
}
You can store the color as an int value in the properties file, as follows:
windowDark.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
getProperties().setProperty("color", Integer.toString(getColor().getRGB()));
}
});
Have the properties as a member of the window this button is in, or even better, in some general location of the application (the class with the main() perhaps ?), and access it with getProperties().
When you need to use the color, parse the string:
Color color = new Color(Integer.parseInt(getProperties().getProperty("color")));
Don't save the properties file on each button click, instead, do so when the application is about to exit:
mainWindow.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
mainWindow.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
try {
File file = new File("DarkTheme.properties");
FileOutputStream fileOut = new FileOutputStream(file);
getProperties().store(fileOut, "Dark theme background colour");
fileOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
mainWindow.dispose();
}
}
});
The change done in memory will be disposed once the application is terminated. If you want to persist some data (in this case, the background color), then you need to store is somewhere, e.g. file, database, etc.
For a simple application, storing your data in a file will be practical.
To do this, you will need to:
- when application starts, read the file, and apply the color specified in the file
- while the application is running and user changes the color, save the color to the same file
To deal with file, you will need to use File, FileReader, and FileWriter classes (all are in java.io package).
I'm trying to find out how to create a JTable cell which contains Image, which should be clickable like an hyperlink. I'm able to load Image using default image renderer.
Can somebody explain me how to add hyperlink (mouse listener) for the each image (cell) in the last column of my table? so that, when the image link in jTable cell is clicked, I want it to open a pop-up with some message showing the error message.
Thanks,
Chandra
To launch link in machine's default browser:
URI uri = null;
try {
uri = new URI(urlToOpen);
} catch (URISyntaxException e1) {
System.out.println("Malformed URI: " + uri);
}
Desktop desktop = Desktop.getDesktop();
try {
desktop.browse(uri);
} catch (IOException e2) {
// If the user default browser is not found, or it fails
// to be launched, or the default handler application
// failed to be launched
JOptionPane.showMessageDialog(null,
"The application could not find any compatible browser.");
}
You can do this on click of Image.
Edit based on comments:
Add listener to image and then you can open a JOptionPane or JDialog on click of Image.
Is it possible to use Java to get a screenshot of an application external to Java, say VLC/Windows Media Player, store it as an Image object and then display it in a JLabel or something of a similar nature? Does anybody know if this is possible and if so does anybody have a general idea as to how to do it?
Note: I just need to find out how to get a screenshot and store it as some form of Image object. After that I can use, manipulate it, display it, etc.
Here is the answer for Windows (not sure if alt+printScr works on linux :P)
I guess one way to achieve this
1. using Robot class to fire alt+printScreen Command (this captures active window to clipboard)
2. read the clipboard!
Here are the two pieces of code that do that. I have not actually tried, but something that I pieced together.
Code to Fire commands to get active window on clipboard
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
public class ActiveWindowScreenShot
{
/**
* Main method
*
* #param args (not used)
*/
public static void main(String[] args)
{
Robot robot;
try {
robot = new Robot();
} catch (AWTException e) {
throw new IllegalArgumentException("No robot");
}
// Press Alt + PrintScreen
// (Windows shortcut to take a screen shot of the active window)
robot.keyPress(KeyEvent.VK_ALT);
robot.keyPress(KeyEvent.VK_PRINTSCREEN);
robot.keyRelease(KeyEvent.VK_PRINTSCREEN);
robot.keyRelease(KeyEvent.VK_ALT);
System.out.println("Image copied.");
}
}
Code to read image on clipboard
// If an image is on the system clipboard, this method returns it;
// otherwise it returns null.
public static Image getClipboard() {
Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
try {
if (t != null && t.isDataFlavorSupported(DataFlavor.imageFlavor)) {
Image text = (Image)t.getTransferData(DataFlavor.imageFlavor);
return text;
}
} catch (UnsupportedFlavorException e) {
} catch (IOException e) {
}
return null;
}
You can manage the control as you need to! Let me know if this works for you. but this is certainly on my todo to try it out!
You can get screen shot of whole screen using class named Robot. Unfortunately you cannot get location and size of windows that belong to other applications using pure java solution. To do this you need other tools (scripting, JNI, JNA). These tools are not cross-platform.