I have developed an application in java swing where two instances have to be run, and I have specified in the code to run a particular instance on a specific screen via configurations. The issue I'm facing is that since it is set as full screen I cannot keep two windows active.
As per requirement I need to keep two windows active in two screens.
The function I used to achieve this is given below.
public static void showOnScreen( int screen, JFrame frame )
{
GraphicsEnvironment ge = GraphicsEnvironment
.getLocalGraphicsEnvironment();
GraphicsDevice[] gs = ge.getScreenDevices();
DisplayMode newDisplayMode;
if( screen > -1 && screen < gs.length )
{
gs[screen].setFullScreenWindow( frame );
}
else if( gs.length > 0 )
{
gs[0].setFullScreenWindow( frame );
}
else
{
throw new RuntimeException( "No Screens Found" );
}
}
Please can someone assist me to solve this issue.
Related
I need to fix the screen location of the Open Source Java Application "Angry IP Scanner" on OSX (https://sourceforge.net/projects/ipscan/) at startup.
If you start the application and move it to the extended space of a secondary monitor (Non mirrored) and do one of two things: 1) Unplug your secondary monitor with the app running or 2) quit the app while it is located on the secondary monitor.
If you unplug the second monitor and then start the app, the app loads and places the screen on the now nonexistent 2nd monitor, even though it is not plugged in.
To get to the screen back to the main screen area you MUST plug in a 2nd monitor and move it back to the main screen. Then you can unplug the second monitor and have no problems.
When the app is starting, I think the app needs to check the current screen size verses the previous screen size and if it has changed, place the screen near the 10,10 location so it will show up on the main, hopefully active screen.
In my searching on Stack Overflow, it appears you can find the current screen information like this:
GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
int width = gd.getDisplayMode().getWidth();
int height = gd.getDisplayMode().getHeight();
How could I save this to a file and recall/compare the previous to the current data, if it has changed, move the application's window to the 10,10 location?
I am a beginner writing iOS and Ruby on OSX, but have not done any Java. I love the program, but this bug is killing me and there doesn't appear to be anyone actively working on the code.
Anyone want to help?
BTW ... It is bug 84 at the Angry IP Scanner website.
Maybe someone could explain how I could run the following code snippet from the cli?
int resolution =Toolkit.getDefaultToolkit().getScreenResolution();
System.out.println(resolution);
Thanks,
padapa
Something like:
public class ShowMeTheScreenSize {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
System.out.println("VirtualBounds = " + getVirtualBounds());
for (int index = 0; index < getScreenDeviceCount(); index++) {
System.out.println("[" + index + "] Device bounds = " + getScreenDeviceBounds(index));
}
System.exit(0);
}
});
}
public static int getScreenDeviceCount() {
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
return ge.getScreenDevices().length;
}
public static Rectangle getVirtualBounds() {
Rectangle bounds = new Rectangle(0, 0, 0, 0);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice lstGDs[] = ge.getScreenDevices();
for (GraphicsDevice gd : lstGDs) {
bounds.add(gd.getDefaultConfiguration().getBounds());
}
return bounds;
}
public static Rectangle getScreenDeviceBounds(int index) {
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice lstGDs[] = ge.getScreenDevices();
return lstGDs[index].getDefaultConfiguration().getBounds();
}
}
Which outputs...
VirtualBounds = java.awt.Rectangle[x=0,y=0,width=3840,height=1200]
[0] Device bounds = java.awt.Rectangle[x=0,y=0,width=1920,height=1200]
[1] Device bounds = java.awt.Rectangle[x=1920,y=0,width=1920,height=1200]
On my machine
As discussed here, Mac OS X helpfully prevents a visible window from being moved offscreen. One expedient would be a command to move the window to a forbidden location, which will force it into reach.
polo.setLocation(Short.MIN_VALUE, Short.MIN_VALUE);
I'm working on a Swing UI in which I want to center multiple components (JDialogs and JFrames). I know that the following code will calculate the user's screen size, and from there, I can easily center a component:
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
For efficiency's sake, I should only calculate this once and store it in some kind of constant so it can be reused in any part of the project. What is the best practice for storing this for later reuse so it is accessible across multiple classes?
(Furthermore, if there is a better way of calculating screen size for centering, I'd be open to hearing that as well)
java.awt.Window.setLocationRelativeTo(null) will center it on the screen whilesetLocationRelativeTo(someComponent) will center it relative to the java.awt.Component, someComponent.
One thing to consider with the alternate of storing the center, is that if a user adjusts their resolution while the program is running than the stored constants will no longer be valid. Is recalling the getScreenSize function actually expensive? (I do not know whether or not it is)
This puts the upper left corner of the component on center, but not the whole component
This means the size of the dialog/frame is (0, 0), Your basic code should be:
frame.add( .... );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible( true );
For centering the object you should try:
The frame position in X = (half frame width) - (half screen size width)
Almost the same for Y = (half frame height) - (half screen size height)
You can easily stores the values in the main class with public access, so you don't need to read them several times
Also, if you do it yourself, you need to factor in the screen's insets using Toolkit.getScreenInsets to account for things like the task bar, which might be on any screen edge and be of any size.
Before I could target Java 1.4, I used:
static public void centerWindow(Window wnd, Component relcom) {
Rectangle scrbnd=getScreenBounds(wnd);
Dimension wndsiz=wnd.getSize();
Container root=null;
int px,py;
if(relcom!=null) {
if(relcom instanceof Window || relcom instanceof java.applet.Applet) {
root=(Container)relcom;
}
else {
Container parent;
for(parent=relcom.getParent(); parent!=null; parent=parent.getParent()) {
if(parent instanceof Window || parent instanceof java.applet.Applet) {
root=parent;
break;
}
}
}
}
if(relcom==null || !relcom.isShowing() || root==null || !root.isShowing()) {
px=(scrbnd.x+((scrbnd.width -wndsiz.width )/2));
py=(scrbnd.y+((scrbnd.height-wndsiz.height)/2));
}
else {
Point relloc=relcom.getLocationOnScreen();
Dimension relsiz=relcom.getSize();
px=(relloc.x+((relsiz.width -wndsiz.width )/2));
py=(relloc.y+((relsiz.height-wndsiz.height)/2));
}
if((px+wndsiz.width )>(scrbnd.x+scrbnd.width )) { px=((scrbnd.x+scrbnd.width )-wndsiz.width ); }
if((py+wndsiz.height)>(scrbnd.y+scrbnd.height)) { py=((scrbnd.y+scrbnd.height)-wndsiz.height); }
if(px<scrbnd.x) { px=scrbnd.x; }
if(py<scrbnd.y) { py=scrbnd.y; }
wnd.setLocation(px,py);
}
I'm doing some Swing GUI work with Java, and I think my question is fairly straightforward; How does one set the position of the mouse?
As others have said, this can be achieved using Robot.mouseMove(x,y). However this solution has a downfall when working in a multi-monitor situation, as the robot works with the coordinate system of the primary screen, unless you specify otherwise.
Here is a solution that allows you to pass any point based global screen coordinates:
public void moveMouse(Point p) {
GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] gs = ge.getScreenDevices();
// Search the devices for the one that draws the specified point.
for (GraphicsDevice device: gs) {
GraphicsConfiguration[] configurations =
device.getConfigurations();
for (GraphicsConfiguration config: configurations) {
Rectangle bounds = config.getBounds();
if(bounds.contains(p)) {
// Set point to screen coordinates.
Point b = bounds.getLocation();
Point s = new Point(p.x - b.x, p.y - b.y);
try {
Robot r = new Robot(device);
r.mouseMove(s.x, s.y);
} catch (AWTException e) {
e.printStackTrace();
}
return;
}
}
}
// Couldn't move to the point, it may be off screen.
return;
}
You need to use Robot
This class is used to generate native system input events for the purposes of test automation, self-running demos, and other applications where control of the mouse and keyboard is needed. The primary purpose of Robot is to facilitate automated testing of Java platform implementations.
Using the class to generate input events differs from posting events to the AWT event queue or AWT components in that the events are generated in the platform's native input queue. For example, Robot.mouseMove will actually move the mouse cursor instead of just generating mouse move events...
Robot.mouseMove(x,y)
Check out the Robot class.
The code itself is the following:
char escCode = 0x1B;
System.out.print(String.format("%c[%d;%df",escCode,row,column));
This code is incomplete by itself, so I recommend placing it in a method and calling it something like 'positionCursor(int row, int column)'.
Here is the code in full (method and code):
void positionCursor(int row, int column) {
char escCode = 0x1B;
System.out.print(String.format("%c[%d;%df",escCode,row,column));
}
I have a Java MouseListener on a component to detect mouse presses. How can I tell which monitor the mouse press occurred in?
#Override
public void mousePressed(MouseEvent e) {
// I want to make something happen on the monitor the user clicked in
}
The effect I'm trying to achieve is: when the user presses the mouse button in my app, a popup window shows some info, until the mouse is released. I want to ensure this window is positioned where the user clicks, but I need to adjust the window position on the current screen so that the entire window is visible.
You can get display information from java.awt.GraphicsEnvironment. You can use this to get a information about your local system. Including the bounds of each monitor.
Point point = event.getPoint();
GraphicsEnvironment e
= GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] devices = e.getScreenDevices();
Rectangle displayBounds = null;
//now get the configurations for each device
for (GraphicsDevice device: devices) {
GraphicsConfiguration[] configurations =
device.getConfigurations();
for (GraphicsConfiguration config: configurations) {
Rectangle gcBounds = config.getBounds();
if(gcBounds.contains(point)) {
displayBounds = gcBounds;
}
}
}
if(displayBounds == null) {
//not found, get the bounds for the default display
GraphicsDevice device = e.getDefaultScreenDevice();
displayBounds =device.getDefaultConfiguration().getBounds();
}
//do something with the bounds
...
Rich's answer helped me find a whole solution:
public void mousePressed(MouseEvent e) {
final Point p = e.getPoint();
SwingUtilities.convertPointToScreen(p, e.getComponent());
Rectangle bounds = getBoundsForPoint(p);
// now bounds contains the bounds for the monitor in which mouse pressed occurred
// ... do more stuff here
}
private static Rectangle getBoundsForPoint(Point point) {
for (GraphicsDevice device : GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()) {
for (GraphicsConfiguration config : device.getConfigurations()) {
final Rectangle gcBounds = config.getBounds();
if (gcBounds.contains(point)) {
return gcBounds;
}
}
}
// if point is outside all monitors, default to default monitor
return GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds();
}
Since Java 1.6 you can use getLocationOnScreen, in previous versions you must get the location of the component that generated the event:
Point loc;
// in Java 1.6
loc = e.getLocationOnScreen();
// in Java 1.5 or previous
loc = e.getComponent().getLocationOnScreen();
You will have to use the GraphicsEnvironment class to get the bound of the screen.
Maybe e.getLocationOnScreen(); will work? It's only for java 1.6.
Leaving this here to help anyone else who may be searching for this:
private int screenIndexOfMouse() {
GraphicsDevice myScreen = MouseInfo.getPointerInfo().getDevice();
GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] allScreens = env.getScreenDevices();
int myScreenIndex = -1;
for (int i = 0; i < allScreens.length; i++) {
if (allScreens[i].equals(myScreen))
{
myScreenIndex = i;
break;
}
}
return myScreenIndex;
}
I do have main application JFrame window which can include different components. I open a self implemented OnScreenKeyboard when the user select a editable textfield. The OSK is also a JFrame window.
When the user drag the main window to another monitor, the OSK should also be shown on the same monitor. For this i have to detect the monitor the main JFrame is shown.
I try to find a method in
Toolkit.getDefaultToolkit()
but was not able to find someting.
Do you know how i can detect the monitor where a JFrame is shown?
Java-Version 1.4
Windows XP
Thanks
Answer, if the solution of all available monitors are the same.
For AWT:
Every Control does have the method getMonitor() from which the screen position get can calculated from like:
Monitor widgetMonitor = mTextWidget.getMonitor();
Rectangle monitorRect = widgetMonitor.getBounds();
if(monitorRect.x < 0){
// shown in left monitor, starting from the main monitor
}
if(monitorRect.x > monitorRect.width){
// shown in right monitor, starting from the main monitor
}
For SWT:
It is just a snip at my origial code. you should ask if return values are not null ans something like this!
int monitorWidth = 0;
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] screenDevices = ge.getScreenDevices();
if(screenDevices.length > 0){
monitorWidth = screenDevices[0].getDisplayMode().getWidth();
}
Point ownerLocationOnScreen = owner.getLocationOnScreen();
int screenMovingX = 0;
if(ownerLocationOnScreen.x < 0){
screenMovingX = -monitorWidth;
}
if(ownerLocationOnScreen.x > monitorWidth){
screenMovingX = monitorWidth;
}