I have the need at my workstation to disable a long idle.
I've been using a piece of code that moves the mouse on the screen once a while, which worked pretty well.
Lately, our security department applied a smart-card&biometric login policy,
which requires my card to be present inside the keyboard (special slot).
Since then the troubles began.
The process works fine as long as I'm logged in, meaning my card is present, but not working if my card is removed.
(I've been logging the process activity, and everything works fine, but the mouse cursor doesn't move.)
Can someone suggest me a way (or link) so I can solve this matter?
Edit
OS: Windows XP
Here's the code that is resposible for moving the mouse.
Notice that I have logged its operation, and tested it: The results outcome logged entries (as if the code was ran) but the mouse cursor wasn't moved on the locked session.
Thanks again
package AntiIdle;
import java.awt.*;
import java.util.Calendar;
import java.text.SimpleDateFormat;
class SimulateMouseAction implements Runnable {
/**
* Robot object used to move the mouse.
*/
private Robot iRobot;
/**
* Bed object, so thread could notify sleeping objects.
*/
private Bed bed;
/**
* Default constructor is neutralized.
*/
#SuppressWarnings("unused")
private SimulateMouseAction () { }
/**
* Constructs class with bed object.
*
* #param bed Bed object to notify the sleepers.
* #throws AWTException if Robot creation fails.
*/
public SimulateMouseAction (Bed bed) throws AWTException {
this.bed = bed;
iRobot = new Robot();
}
/**
* Activates tread.
*/
public void run() {
System.out.println(new SimpleDateFormat("d/M/yy hh:mm").format(Calendar.getInstance().getTime()) +
"Mouse start");
Dimension scrSize = Toolkit.getDefaultToolkit().getScreenSize();
int x, y;
for (int prcnt=0; prcnt<100; prcnt++) {
x = (int) scrSize.getWidth() * prcnt / 100;
y = (int) scrSize.getHeight() * prcnt / 100;
moveMouse(x, y);
}
y = (int) scrSize.getHeight() - 20;
for (int prcnt=100; prcnt>0; prcnt--) {
x = (int) scrSize.getWidth() * prcnt / 100;
moveMouse(x, y);
}
for (int prcnt=0; prcnt<100; prcnt++) {
x = (int) scrSize.getWidth() * prcnt / 100;
y = (int) scrSize.getHeight() * (100-prcnt) / 100;
moveMouse(x, y);
}
iRobot.mouseMove((int) scrSize.getWidth()/2, (int) scrSize.getHeight()/2);
System.out.println(new SimpleDateFormat("d/M/yy hh:mm").format(Calendar.getInstance().getTime()) +
"Mouse end");
bed.awakeTheSleepers();
}
/**
* Moves mouse cursor to given coordinates.
*
* #param x X coordinate.
* #param y Y coordinate.
*/
private void moveMouse(int x, int y) {
iRobot.mouseMove(x, y);
try {
Thread.sleep(10);
} catch(InterruptedException ie) {
ie.printStackTrace();
}
}
}
Edit
#Mark Peters: Thanks for repling. As funny as it seems, they gave me this solution... I've built a java application which launches some vb script that loads Excel and performs some tasks and create reports. The problem is that it stops launching Excel after a day of idle on my station. Everything else seem to be working (The java application keeps working-I've been logging its activity as well as the mouse mover activity in the attached code above). So as you can see, the security problem you suggested isn't solved either way. As a rule at my country, I'm forced to have 1 week of vacation in a row at least once a year. Ironically, this what's preventing me from fulfilling this duty.
Any suggestion?
Related
I want to, if the player breaks a block, break the block above, too, but this code will just drop the original block (brokenBlock) and not even break the block above...
What did I do wrong?
#EventHandler
public void onDestroy(BlockBreakEvent event)
{
Player player = event.getPlayer();
if (player.getItemInHand().getType() == Material.WOOD_PICKAXE)
{
Location brokenBlock = event.getBlock().getLocation();
Location up = brokenBlock.add(0, 1, 0);
up.getBlock().breakNaturally();
}
}
After some experimenting, I found the problem, but not the answer.
I made the code above shorter, so it's nicer to read, but the original contains two breakNaturally() methods.When I try to execute both or more, it acts strangely and doesn't work anymore.
Here's the real code:
#EventHandler
public void onDestroy(BlockBreakEvent event)
{
Player player = event.getPlayer();
if (player.getItemInHand().getType() == Material.WOOD_PICKAXE)
{
Location brokenBlock = event.getBlock().getLocation();
Location up = brokenBlock.add(0, 1, 0);
Location down = brokenBlock.add(0, -1, 0);
up.getBlock().breakNaturally();
down.getBlock().breakNaturally();
}
}
Note: Relevant links to resources to CraftBukkit code are now unavailable due to Bukkit being taken down by DMCA requests, they will be linked to Bukkit-Bleeding and be subject to link rot.
Contrary to your belief, Location objects are not #Immutable (as in immutability of object, not the annotation). Firstly, here you have the source code for Location.add(double, double, double):
/**
* Adds the location by another. Not world-aware.
*
* #see Vector
* #param x X coordinate
* #param y Y coordinate
* #param z Z coordinate
* #return the same location
*/
public Location add(double x, double y, double z) {
this.x += x;
this.y += y;
this.z += z;
return this;
}
As you can see, the fields change and returns itself in the process. This is because the location manipulations reuse itself for efficiency, instead of having to call new constructs and cache objects.
You're better off using them every time you change them:
/* (BlockBreakEvent event) */ {
Location brokenBlock = event.getBlock().getLocation();
for (int i = 1; i < 16; i++)
brokenBlock.add(0, i, 0).getBlock().breakNaturally();
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Okay, I'm just a greenhorn here and I'm trying some various codes. Now this game GUI src I found have some image files inside a folder and its a necessity for the whole game to work.
I tried some methods, but I just can't understand how can I make the src connected to the folder. The program runs now but it only displays black screen because it can't connect to the images. Please, I need help.
What I just wanted is how can I make the program recognize the files I'm using as background images and such. The code line is there, but it displays an exception...
Am I still unclear? ._.
Well it goes like this:
package moon_lander;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
/**
* Actual game.
*
* #author www.gametutorial.net
*/
public class Game {
/**
* The space rocket with which player will have to land.
*/
private PlayerRocket playerRocket;
/**
* Landing area on which rocket will have to land.
*/
private LandingArea landingArea;
/**
* Game background image.
*/
private BufferedImage backgroundImg;
/**
* Red border of the frame. It is used when player crash the rocket.
*/
private BufferedImage redBorderImg;
public Game()
{
Framework.gameState = Framework.GameState.GAME_CONTENT_LOADING;
Thread threadForInitGame = new Thread() {
#Override
public void run(){
// Sets variables and objects for the game.
Initialize();
// Load game files (images, sounds, ...)
LoadContent();
Framework.gameState = Framework.GameState.PLAYING;
}
};
threadForInitGame.start();
}
/**
* Set variables and objects for the game.
*/
private void Initialize()
{
playerRocket = new PlayerRocket();
landingArea = new LandingArea();
}
/**
* Load game files - images, sounds, ...
*/
private void LoadContent()
{
try
{
URL backgroundImgUrl = this.getClass().getResource("/moon_lander/resources/images/background.jpg");
backgroundImg = ImageIO.read(backgroundImgUrl);
URL redBorderImgUrl = this.getClass().getResource("/moon_lander/resources/images/red_border.png");
redBorderImg = ImageIO.read(redBorderImgUrl);
}
catch (IOException ex) {
Logger.getLogger(Game.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Restart game - reset some variables.
*/
public void RestartGame()
{
playerRocket.ResetPlayer();
}
/**
* Update game logic.
*
* #param gameTime gameTime of the game.
* #param mousePosition current mouse position.
*/
public void UpdateGame(long gameTime, Point mousePosition)
{
// Move the rocket
playerRocket.Update();
// Checks where the player rocket is. Is it still in the space or is it landed or crashed?
// First we check bottom y coordinate of the rocket if is it near the landing area.
if(playerRocket.y + playerRocket.rocketImgHeight - 10 > landingArea.y)
{
// Here we check if the rocket is over landing area.
if((playerRocket.x > landingArea.x) && (playerRocket.x < landingArea.x + landingArea.landingAreaImgWidth - playerRocket.rocketImgWidth))
{
// Here we check if the rocket speed isn't too high.
if(playerRocket.speedY <= playerRocket.topLandingSpeed)
playerRocket.landed = true;
else
playerRocket.crashed = true;
}
else
playerRocket.crashed = true;
Framework.gameState = Framework.GameState.GAMEOVER;
}
}
/**
* Draw the game to the screen.
*
* #param g2d Graphics2D
* #param mousePosition current mouse position.
*/
public void Draw(Graphics2D g2d, Point mousePosition)
{
g2d.drawImage(backgroundImg, 0, 0, Framework.frameWidth, Framework.frameHeight, null);
landingArea.Draw(g2d);
playerRocket.Draw(g2d);
}
/**
* Draw the game over screen.
*
* #param g2d Graphics2D
* #param mousePosition Current mouse position.
* #param gameTime Game time in nanoseconds.
*/
public void DrawGameOver(Graphics2D g2d, Point mousePosition, long gameTime)
{
Draw(g2d, mousePosition);
g2d.drawString("Press space or enter to restart.", Framework.frameWidth / 2 - 100, Framework.frameHeight / 3 + 70);
if(playerRocket.landed)
{
g2d.drawString("You have successfully landed!", Framework.frameWidth / 2 - 100, Framework.frameHeight / 3);
g2d.drawString("You have landed in " + gameTime / Framework.secInNanosec + " seconds.", Framework.frameWidth / 2 - 100, Framework.frameHeight / 3 + 20);
}
else
{
g2d.setColor(Color.red);
g2d.drawString("You have crashed the rocket!", Framework.frameWidth / 2 - 95, Framework.frameHeight / 3);
g2d.drawImage(redBorderImg, 0, 0, Framework.frameWidth, Framework.frameHeight, null);
}
}
}
And this is the Exception:
Exception in thread "Thread-2" java.lang.IllegalArgumentException: input == null!
at javax.imageio.ImageIO.read(ImageIO.java:1362)
at moon_lander.Framework.LoadContent(Framework.java:115)
at moon_lander.Framework.GameLoop(Framework.java:162)
at moon_lander.Framework.access$000(Framework.java:21)
at moon_lander.Framework$1.run(Framework.java:90)
Process completed.
How you load imagines doesn't have anything to do with packages.
Normally you find an image as a resource via class path. This can be arranged any way you wish.
I tried some methods, but I just can't understand how can I make the src connected to the folder.
Usually you build an application. When you run it, you use the build, not the src. i.e. you don't use the source when you run the program. Usually the images are copied with the same relative path you used in your source and this relative path is what you use to find and load your images.
I can't be more specific, as there is not enough detail in the questions such as what you directory structure is and which IDE or build system you are using.
Occasionally I have to display a popup or dialog relative to an existing component (prime example is a date input control with a calendar button beside it).
It worked beautifully for years, but always had the bug that the calendar could partially appear outside the screen (it was hardcoded to appear just to the right of the field). Just nobody ever noticed because there was never a date control at the far right in a window. Well that changed recently with the addition of a new window.
Well then, I thought, lets just fix a windows position (after I positioned it where it should be) to be completely on screen. I wrote a simple utility method to do just that:
public static void correctWindowLocationForScreen(Window window) {
GraphicsConfiguration gc = window.getGraphicsConfiguration();
Rectangle screenRect = gc.getBounds();
Rectangle windowRect = window.getBounds();
Rectangle newRect = new Rectangle(windowRect);
if (windowRect.x + windowRect.width > screenRect.x + screenRect.width)
newRect.x = screenRect.x + screenRect.width - windowRect.width;
if (windowRect.y + windowRect.height > screenRect.y + screenRect.height)
newRect.y = screenRect.y + screenRect.height - windowRect.height;
if (windowRect.x < screenRect.x)
newRect.x = screenRect.x;
if (windowRect.y < screenRect.y)
newRect.y = screenRect.y;
if (!newRect.equals(windowRect))
window.setLocation(newRect.x, newRect.y);
}
Problem solved. Or not. I position my window using the on-screen coordinates from the triggering component (the button that makes the calendar appear):
JComponent invoker = ... // passed in from the date field (a JButton)
Window owner = SwingUtilities.getWindowAncestor(invoker);
JDialog dialog = new JDialog(owner);
dialog.setLocation(invoker.getLocationOnScreen());
correctWindowLocationForScreen(dialog);
Havoc breaks out if the "invoker" component is located in a window that spans two screens. Apparently "window.getGraphicsConfiguration()" returns whatever graphic configuration the windows top left corner happens to be in. Thats not necessarily the screen where the date component within the window is located.
So how can I position my dialog properly in this case?
One can iterate over all devices, and find the monitor where the point is in. Then keep to that Rectangle.
See GraphicsEnvironment.getScreenDevices.
This will not use the current Window, but you already found out that a window may be shown in several monitors.
Useful might be Component.getLocationOnScreen.
Ok, here is what I ended up with (a wall of code to handle the odd edge case).
correctWindowLocationForScreen() will reposition a window if it is not completely within the visible screen area (simplest case, its completely on one screen. Hard case, it spans multiple screens). If the window leaves the complete screen area by just one pixel, it is repositioned using the first screen rectangle found. If the window doesn't fit the screen, its positioned at the top left and extends over the screen to bottom right (its implied by the order in which positionInsideRectangle() checks/alters coordinates).
Its quite complicated considering the requirement is pretty simple.
/**
* Check that window is completely on screen, if not correct position.
* Will not ensure the window fits completely onto the screen.
*/
public static void correctWindowLocationForScreen(final Window window) {
correctComponentLocation(window, getScreenRectangles());
}
/**
* Set the component location so that it is completely inside the available
* regions (if possible).
* Although the method will make some effort to place the component
* nicely, it may end up partially outside the regions (either because it
* doesn't fit at all, or the regions are placed badly).
*/
public static void correctComponentLocation(final Component component, final Rectangle ... availableRegions) {
// check the simple cases (component completely inside one region, no regions available)
final Rectangle bounds = component.getBounds();
if (availableRegions == null || availableRegions.length <= 0)
return;
final List<Rectangle> intersecting = new ArrayList<>(3);
for (final Rectangle region : availableRegions) {
if (region.contains(bounds)) {
return;
} else if (region.intersects(bounds)) {
// partial overlap
intersecting.add(region);
}
}
switch (intersecting.size()) {
case 0:
// position component in the first available region
positionInsideRectangle(component, availableRegions[0]);
return;
case 1:
// position component in the only intersecting region
positionInsideRectangle(component, intersecting.get(0));
return;
default:
// uuuh oooh...
break;
}
// build area containing all detected intersections
// and check if the bounds fall completely into the intersection area
final Area area = new Area();
for (final Rectangle region : intersecting) {
final Rectangle2D r2d = new Rectangle2D.Double(region.x, region.y, region.width, region.height);
area.add(new Area(r2d));
}
final Rectangle2D boundsRect = new Rectangle2D.Double(bounds.x, bounds.y, bounds.width, bounds.height);
if (area.contains(boundsRect))
return;
// bah, just place it in the first intersecting region...
positionInsideRectangle(component, intersecting.get(0));
}
/**
* Position component so that its completely inside the rectangle.
* If the component is larger than the rectangle, component will
* exceed to rectangle bounds to the right and bottom, e.g.
* the component is placed at the rectangles x respectively y.
*/
public static void positionInsideRectangle(final Component component, final Rectangle region) {
final Rectangle bounds = component.getBounds();
int x = bounds.x;
int y = bounds.y;
if (x + bounds.width > region.x + region.width)
x = region.x + region.width - bounds.width;
if (y + bounds.height > region.y + region.height)
y = region.y + region.height - bounds.height;
if (region.x < region.x)
x = region.x;
if (y < region.y)
y = region.y;
if (x != bounds.x || y != bounds.y)
component.setLocation(x, y);
}
/**
* Gets the available display space as an arrays of rectangles
* (there is one rectangle for each screen, if the environment is
* headless the resulting array will be empty).
*/
public static Rectangle[] getScreenRectangles() {
try {
Rectangle[] result;
final GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
final GraphicsDevice[] devices = ge.getScreenDevices();
result = new Rectangle[devices.length];
for (int i=0; i<devices.length; ++i) {
final GraphicsDevice gd = devices[i];
result[i] = gd.getDefaultConfiguration().getBounds();
}
return result;
} catch (final Exception e) {
return new Rectangle[0];
}
}
I' m currently writing a simple 2D game in java from scratch (for learning purposes)
I want to control the rate at which a player can shoot. The method done there works, but it could be improved. The method is getting called if the user presses/holds the left mouse button. It works when the user is holding the button pressed, but when he/she releases the mouse button, waits (more then the rateOfFire time) and tries to shoot it may or may not work, because the roftC value isn' t getting updated when the player doesn' t shoot.
I tried then to put it into my update() method (which gets called 60 times a second). The problem still exists. I really have no idea how to solve this. Here is my code:
/**
* Used to control the rate of fire
*/
private int roftC = 0;
/**
* Shoot a Projectile
*/
protected void shoot(int x, int y, double dir) {
Projectile p = new Bomb(x, y, dir);
if (roftC % p.getRateOfFire() == 0) {
level.addProjectile(p);
}
if (roftC > 6000) {
roftC = 0;
}
roftC++; // Whether it is here or down there doesn' t make a diffrence
}
/**
*
*/
#Override
public void update() {
// roftC++;
}
One idea would be to introduce a minimum delay between shots. Something like this:
static final long MINIMUM_DELAY = 1000/30; // So we can have 30 shots per second
long lastShotTimestamp;
protected void shoot(int x, int y, double dir) {
long now = System.currentTimeMillis();
if (now - lastShotTimestamp > MINIMUM_DELAY) {
level.addProjectile(new Bomb(x, y, dir));
lastShotTimestamp = now;
}
}
Such an approach is actually close to the physics - a gun needs some time to reload between consecutive shots.
This is a program I wrote for creating a pacman. I now want the Pacman to move in a straight line from a random start point to a random goal point.
Could you please suggest how to do it.
import javax.swing.JFrame;
/**
* Main class for pacman example. All it does is create a frame and put
* the pacman panel in it.
*/
public class PacmanGUI extends JFrame{
private Pacman pc;
public PacmanGUI(){
super("Pacman");
pc = new Pacman();
this.getContentPane().add(pc);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
this.setVisible(true);
}
public static void main(String[] args) {
new PacmanGUI();
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/**
* Pacman class that extends JPanel and paints a pacman animation.
* It uses Timers and Actionlistener to do the Animation.
*
*/
public class Pacman extends JPanel implements ActionListener{
private int figureSize = 50;
private static final int DELAY = 200;
private double mouthOpenPercentages[] = {.1,.5};
private Timer animationTimer;
private int mouthState = 0;
private Point pacManPosition;
/**
* No args constructor that starts the animation.
*/
public Pacman(){
startAnimation();
}
/**
* Overriden paintComponent method that paints pacman.
*/
public void paintComponent(Graphics g) {
super.paintComponent(g);
pacManPosition = new Point(this.getWidth()/2 - figureSize/2,
this.getHeight()/2 - figureSize/2);
g.fillRect(0,0,this.getWidth(), this.getHeight());
drawPacMan(g);
mouthState = (++mouthState) % mouthOpenPercentages.length;
}
/**
* Stops the animation by stopping the animation timer.
*/
public void stopAnimation(){ animationTimer.stop(); }
/**
* Method do deal with actionevents that are triggered. In this
* case we only have actionevents being triggered from our timer
* and by the more usual case of a button click.
*/
public void actionPerformed(ActionEvent e){ repaint(); }
/**
* Gets the size that this component would like to be.
*/
public Dimension getPreferredSize(){ return new Dimension(400,400); }
/**
* Gets the minimum size for this component.
*/
public Dimension getMinimumSize(){ return new Dimension(200,200); }
/**
* Starts the animation by setting a timer. When this timer goes
* off the actionPerformed method will be triggered, which in
* turn triggers the painting.
*/
private void startAnimation(){
if (animationTimer == null){
mouthState = 0;
animationTimer = new Timer(DELAY, this);
animationTimer.start();
} else { //continue animating..
if (!animationTimer.isRunning())
animationTimer.restart();
}
}
/**
* Draws our little pacman on the given graphics canvas.
* #param g
*/
private void drawPacMan(Graphics g){
Color c = g.getColor();
g.setColor(Color.yellow);
g.fillOval(pacManPosition.x, pacManPosition.y, figureSize, figureSize);
//Change color back to original and draw pacman's mouth
g.setColor(c);
//calculate mouth offsets
int yOffset = (int)((figureSize/2)*mouthOpenPercentages[mouthState]);
//draw the mouth cutout.
int x[] = {pacManPosition.x + figureSize/2, pacManPosition.x + figureSize, pacManPosition.x + figureSize};
int y[] = {pacManPosition.y + figureSize/2,
pacManPosition.y + figureSize/2 + yOffset,
pacManPosition.y + figureSize/2 - yOffset};
g.fillPolygon(x, y, x.length);
}
}
Inside the Pacman class you would need to create 2 more values to store the start and end points. You already have private Point pacManPosition; declared so I would also declare these as Points. You'll want to set pacManPosition initially to the start point.
Point start = // random start point
Point end = // random end point
Point pacManPoint = new Point(start);
Now you'll want to determine the speed you want your Pacman to move at, let's say 2 pixels per frame.
int speed = 2;
To determine how much to move the Pacman each frame, we'll need to do some calculations. First, get the distance of the line -
double distance = Math.sqrt(Math.pow(end.x - start.x, 2) +
Math.pow(end.y - start.y, 2));
Then we calculate how many frames it will take to go that distance at the speed we want.
int totalFrames= (int)Math.round(distance / speed);
And add a frame counter -
int frame = 0;
Now, look inside your paintComponent method. Right now you're setting pacManPosition to the same point (the center of the panel) each time it paints. What you want to do here instead is to update pacManPosition each frame until it gets to the end position. You're doing something similar lower in paintComponent where you're updating mouthState each time to get the mouth to animate. For animating position it will look like -
if (frame < totalFrames) {
pacManPosition.x = start.x + frame * (end.x - start.x) / totalFrames;
pacManPosition.y = start.y + frame * (end.y - start.y) / totalFrames;
frame++;
}
This is only one way to do movement animation, and it assumes several things - constant speed, no need to avoid obstacles, no player control. The calculation in totalFrames isn't exact - it moves pacMan close to the end point, but there's no guarantee it will end exactly there. It is also tied to the frame rate, which has drawbacks. There are many, many other ways to do this depending on the situation.
Problem
You have to manage two animations at the same time.
The first, which you've already coded, opens and closes the Pacman's mouth.
The second animation is responsible for moving the Pacman from one location to another.
Solution - Sprite class
I suggest you create a Sprite class. The Sprite class would be responsible for holding the current position of the sprite, the next position of the sprite, and the speed at which the sprite moves.
You would extend Sprite to get one Pacman class, and a Chaser class with 4 instances.
Pacman class
The Pacman class would be responsible for the mouth animation.
Chaser class
The Chaser class would be responsible for determining whether to chase the Pacman, or run away from the Pacman.
Swing Tips
You should not extend Java Swing components, unless you are overriding one or more of the component classes. You should use Swing components.
You should always start your Swing GUI on the Event Dispatch Thread (EDT). You do this by executing the invokeLater method of SwingUtilities.
You should have a GUI model, separate from your GUI components. The three classes I defined would be part of your GUI model. You also need to lay out a maze.