Is there a way to figure out the first drag movement of the mouse in Java?
For example:
public void mouseDragged(MouseEvent e)
{
if (first drag of the mouse) // what should I write here?
System.out.println("This is the first drag");
else System.out.println("This isn't the first drag");
}
If I drag the mouse 5 times I should see this text in the console:
This is the first drag
This isn't the first drag
This isn't the first drag
This isn't the first drag
This isn't the first drag
boolean first=true;//this should be a instance variable.
first drag! use a boolean variable to detect first or not.like this
public void mouseDragged(MouseEvent e)
{
if (first) { // this is only true if it's first drag
System.out.println("This is the first drag");
first=false;
}
else {
System.out.println("This isn't the first drag");
}
}
update...
this is how u can detect is it first drag.but there are a problem normally mouse drag event triggered while dragging.to avoid this u can modify this little bit.
declare instance variables
boolean draging = true;
boolean mark = true;
boolean first = true;
print only when dragging start.when we print mouse dragging we stop printing it until mouse released and redragging.
public void mouseDragged(java.awt.event.MouseEvent evt) {
draging = true;
if (mark) {
if (first) {
System.out.println("This is the first drag");
}else{
System.out.println("This isn't the first drag");
}
mark = false;
}
}
change first to false so first dragging is enough.and ready for print new drag[mark = true]
public void mouseReleased(java.awt.event.MouseEvent evt) {
if (draging) {
mark = true;
first=false;
}
}
this is the output of 1st and updated examples.there is a problem of 1st code [because event drag is triggered continuously while dragging ,not ones].
first example
This is the first drag
This is the first drag
This is the first drag
.............................//this continues until u finish[released] first drag
This isn't the first drag
This isn't the first drag
This isn't the first drag
................................
updated one
This is the first drag //a drag [ click--move--relesed] mark only 1time
This isn't the first drag
This isn't the first drag
This isn't the first drag
...............................
I would modify FastSnails solution to this slightly to get around the behaviour that mouseDragged fires on every mouse movement while the button is down:
boolean first = true;
boolean triggered = false;
public void mouseDragged(MouseEvent e){
if(!triggered){
if(first){
System.out.println("This is the first drag");
first=false;
}
else{
System.out.println("This isn't the first drag");
}
triggered = true;
}
}
Of course, we then have to reset that flag in a mouseReleased event, which signals the end of the "drag":
public void mouseReleased(MouseEvent e){
triggered = false;
}
Using this method means that the message only gets triggered once per "drag", rather than at every mouse movement.
Related
I am writing a board game where I need to check for enemies on the the player is moving and prompt to make an attack. However because of how the game is made the move method is called on the JavaFX application thread, I want to be able to prompt the user if they want to fight an enemy.
My dialogue box which works fine normal uses wait and notify which dont work on the main thread without crashing the program, does anyone know how to pause the execution of this thread until a user clicks one of the buttons.
I apologise for the description, its late.
Method that checks for enemies
This method checks for the enemies and returns the enemy if the user selected yes. It runs on the JavaFX Thread.
private Ship pathBattle(Vector gridPosition){
//Check if there are ships on the path to the destination
for(Button cell : activeButtons){
//Check the button position is not that of the current button, dont go past the current button
Vector pixPosition = new Vector(cell.getLayoutX(), cell.getLayoutY());
//Convert to a grid referance
Vector gridPos = Vector.pixToGrid(pixPosition);
if(!gridPos.equals(gridPosition)){
//This button is not the destination
//Check for any ships on that cell
Ship collided = Ship.isOccupiedButton(cell);//Returns the ship if there is one on the cell
if(collided != null){
//There is a ship, prompt to battle
boolean battle = UtilPopups.showConfirmationDialog("Do you want to battle " + collided.getName(), "YAR!", "NAY!");
Game.printError("Ship collision");
if(battle){
return collided; //Return the ship to battle
}
}
}
//On to the next button
}
return null;
}
The code to display the Popup
This does work in other areas of the porgram with no issue
public static boolean showConfirmationDialog(String lblPrompt, String btnYes, String btnNo){
//Check if the confirmation controller is not null
if(confirmationDialog != null){
confirmationDialog.lbl_prompt.setText(lblPrompt);
confirmationDialog.btn_no.setText(btnNo);
confirmationDialog.btn_yes.setText(btnYes);
//Show the base
show(confirmationDialog.base_pane);
//Pause this thread until user input is given from GUI thread
synchronized (confirmationDialog) {
try{
confirmationDialog.wait();
} catch (Exception e) {
e.printStackTrace();
}
}
//Program resumed, user input given and stored in response
if(confirmationDialog.response.equals("yes")){
confirmationDialog.response = null; //Set back to null
return true;
} else {
confirmationDialog.response = null; //Set back to null
return false;
}
}
//Class not initialized
Game.printError("UtilPopups->showConfirmationDialog: Dialog NULL!");
return false;
}
For blocking any caller thread during showing dialog, for example:
static private void showAndBlock(Dialog dialog) {
if (Platform.isFxApplicationThread()) {
dialog.showAndWait();
} else {
CountDownLatch lock = new CountDownLatch(1);
Platform.runLater(() -> {
dialog.showAndWait();
lock.countDown();
});
try {
lock.await();
} catch (InterruptedException e) {
// Just in case you call yourTherad.interrupt(),
// the thread will be joined forcibly through here.
}
}
}
But I'm not sure whether or not it works in your threading design.
The collided method literally doesnt nothing, it doesn't ask for a input so it can't work.
I think, sorry not good english
My method some reason doesnt work I want it so when I click tab it grabs the mouse and moves the player but when clicked again I want it to release the mouse and stop the players rotation I tried putting a print statement into the movePlayerWithMouse method but it just returns true the only thing that does change is the mouse each time I click tab it releases and grabs any help?
Heres the method I use:
boolean movePlayerWithMouse = false;
while(Keyboard.next()) {
if(!Keyboard.getEventKeyState()) {
if(Keyboard.getEventKey() == Keyboard.KEY_TAB) {
movePlayerWithMouse = !movePlayerWithMouse;
Mouse.setGrabbed(!Mouse.isGrabbed());
}
}
}
if(movePlayerWithMouse = !movePlayerWithMouse) {
rotY -= Mouse.getDX() / SENSITIVITY;
}
Because of many boolean checks i am a little confused, let me introduce me to my next code.
} else {
//check whether the player starts again. the first time we lose the player
//will definitely get into this loop
if(!startAgain){
// we only do this to set a timer, we don't want to start a new game so we set this
// to false
newgame = false;
startAgain = true;
deadTime = System.nanoTime();
}
deadTimepassed = (System.nanoTime() - deadTime)/1000000;
if((deadTimepassed < 2000) && (newgame = false)){
newGame();
}
}
}
This else statement can be seen as the first time a player gets hit by an enemy missile. To make an explosion-animation. I need te screen to freeze for 2 seconds and then start the game over again. I don't see why the second if statement is never reached. Here are my ontouch methods and my new game method:
#Override
public boolean onTouchEvent(MotionEvent event) {
//What happens when the player touches the screen!
if (event.getAction() == MotionEvent.ACTION_DOWN) {
// Boolean check for when player is playing, if he isn't the chopper does nothing.
// we see that the chopper only hangs still if all these booleans are true!
if ((!player.isPlaying()) && (newgame = true) && (startAgain = true)) {
player.setPlaying(true);
} if(player.isPlaying()) {
player.setUp(true);
startAgain = false;
}
return true;
}
if (event.getAction() == MotionEvent.ACTION_UP) {
player.setUp(false);
return true;
}
return super.onTouchEvent(event);
}
public void newGame(){
newgame = true;
missles.clear();
if(player.getScore()>best) {
best = player.getScore();
SharedPreferences.Editor editor = saveBest.edit();
editor.putInt("new best",best);
editor.commit();
}
player.resetScore();
player.setY(HEIGHT/2);
}
As one can see, the new game just resets the players position, the only thing i want to do is just freeze the screen for 2 seconds before that happens, this is supposed to happen in the second if statement but it never get reached...
Any suggestions?
ps: deadTimepassed is introduced as 'private long' just beneath the public class method.
For freeze your Thread (so, the program will be freeze, also your screen) during 2 seconds you can use Thread.sleep() function:
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
You have to put it inside a try-catch block because it can gives to you an InterruptedException.
I expect it will be helpful for you!
Hi I'm new to stackoverflow so bear with me if I make mistakes.
I'm making this Java Simon Says Game for a class project. It works by a random number generator for each sequence#. I show the sequence through doClick() but remove the actionlisteners beforehand and add it afterwards.
The problem is the buttons won't unpress or unarm until all other buttons have been pressed. I've tried using thread.sleep to put a delay between each if...else statements yet it only stays pressed for longer. I've tried updating the gui through repaint(), revalidate(), updateUI() within the try... catch of the thread.sleep but that didn't work either.
I've realized this issue is mainly cosmetic because when I tried implementing setPressed or setArmed it said it wasn't being pressed but it looked pressed.
Here is the code snippet in it's most simplest form without thread.sleep or my previous attempts in comments.
public void sequence2() //This is where the issue happens. The buttons won't unpress until every button has been pressed.
{
level.setText(" Level 2"); //Level indicator
Green.removeActionListener(Listener);
Red.removeActionListener(Listener);
Yellow.removeActionListener(Listener);
Blue.removeActionListener(Listener);
if(sequence1 == 1)
{
Green.doClick(300); //Programmatically clicks the button
}
else if(sequence1 == 2)
{
Red.doClick(300);
}
else if(sequence1 == 3)
{
Yellow.doClick(300);
}
else if(sequence1 == 4)
{
Blue.doClick(300);
}
if(sequence2 == 1)
{
Green.doClick(300);
}
else if(sequence2 == 2)
{
Red.doClick(300);
}
else if(sequence2 == 3)
{
Yellow.doClick(300);
}
else if(sequence2 == 4)
{
Blue.doClick(300);
}
Green.addActionListener(Listener);
Red.addActionListener(Listener);
Yellow.addActionListener(Listener);
Blue.addActionListener(Listener);
}
I'm very new to java so I'm not skilled in multithreading or working on the Event Dispatch Thread for that manner. But if that's the only solution I'll need some more help with that.
I have the full code in a zip file with previous attempts commented out if that will help.
https://drive.google.com/file/d/0Bxg4WleC9jD2VFhoZmZBNjV6Vkk/view?usp=sharing
Invoking doClick() may be an awkward choice for this, as it uses a Timer internally. Instead, use a JToggleButton, which will allow you to control each button's appearance based on its selected state using setSelected(). A complete example is shown in the game Buttons. In the ActionListener of your Swing Timer, select the current button, play its note and increment the sequence index. When all notes have been played, unselect all the buttons.
Addendum: Can you show how you implement the timer?
In outline, given a suitable list of toggle buttons:
private static final int MAX = 4;
List<JToggleButton> buttons = new ArrayList<JToggleButton>(MAX);
private int i;
The timer's listener might look like this:
#Override
public void actionPerformed(ActionEvent e) {
Object src = e.getSource();
JToggleButton b = buttons.get(i);
if (i > MAX) { // reset i and all the buttons
for (JToggleButton b : buttons) {
b.setSelected(false);
}
timer.stop();
i = 0;
} else {
b.setSelected(true);
// play tone i
i++;
}
}
A toggle button's item listener should update the button's appearance as indicated by its state:
#Override
public void itemStateChanged(ItemEvent e) {
JToggleButton b = (JToggleButton) e.getItem();
if (b.isSelected()) {
// change icon, color etc.
} else {
// restore icon, color etc.
}
}
I'm making a small game project in Java. In it you have a character that shoots in the direction of the mouse when "pressed" or "dragged" (you know, in Java's terms). The only problem is that if you stop dragging but you still hold the left mouse button down you stop shooting.
Is there a way to detect if the mouse button is down after a drag?
NOTE: the mouse is not sensed as "pressed" after the drag.
You will get the information when a mouse button is pressed and when it is released again. If you want to know the state in between, you need to use a boolean to store that information.
Example:
final boolean[] buttonStates = new boolean[3];
public void mousePressed(MouseEvent e) {
buttonStates[e.getButton()] = true;
}
public void mouseReleased(MouseEvent e) {
buttonStates[e.getButton()] = false;
}
You would do the same for keyboard input by the way.