Getting character to jump in JavaFX - java

I have tried using a KeyListener to make the character rise which just simply didnt do anything. Is there a better way to do this? If not, does anyone know why the KeyListener isn't working? I would really appreciate some help. Also, I call this method in a Timeline so the bird does not just fall 1 pixel and will not rise by one either
Here is the code for the KeyListener (The bird falling part works fine by the way):
public static void birdJump() {
birdView.relocate(100, fall++);
if(fall > 201)
birdView.setRotate(50);
FlappyBird.root.setOnKeyPressed(new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent event) {
if (event.getCode().equals(32)) {
birdView.relocate(100, fall--);
if(fall > 199)
birdView.setRotate(-50);
}
}
});
}
Thanks!

Read the documentation: event.getCode() does not return an int (or a number of any kind), so event.getCode().equals(32) cannot possibly be true.
You want
if (event.getKeyCode() == KeyCode.SPACE) {
// ...
}

In addition to what James_D said, I think it's because you use the KeyEvent on a Layout that does not have the focus by default since it belongs to the Scene, to remedy it you have to give it the focus :
root.setFocusTransversale(true); /* Enable focus on the layout */
root.requestFocus(); /* give the focus to the layout */
I hope this will solve your problem !

Related

removeEvent ItemListener (removeItemListener) from within itemStateChanged doesn't work (StackOverfowError)

I have the following code, I cannot use setEnabled(false), because I need to set the background- and foregroundcolor.
public class RadioButton extends JRadioButton implements ItemListener {
public RadioButton(String text)
{
super(text);
addItemListener(this);
}
public void itemStateChanged(ItemEvent e) {
synchronized (this) {
removeItemListener(this);
if (e.getStateChange() == ItemEvent.SELECTED) {
System.out.println("item is selected true [changed]");
setSelected(false);
} else if (e.getStateChange() == ItemEvent.DESELECTED) {
System.out.println("item is selected false [changed]");
setSelected(true);
}
addItemListener(this);
}
}
}
This should be a radio button, that can't be changed. Hoever if I try testing the code, it gives me an endless loop printing
item is selected true [changed]
once...
...and then always
item is selected false [changed]
until there is a Java StackOverflowError.
How can this be? Is the disabling of the ItemListener not working?
If you can then please also show me, how to pack this into a lamda function. I got a illegal self reference-error, when trying to put this into a lamda function.
Please correct me, if the title is not correct.
As MadProgrammer pointed out, disabling the AbstractButton (aka RadioButton or Checkbox) can be archieved by setting the ButtonModel to a custom one always returning a constant value.
MainClass:
radioButtonOrCheckbox.setModel(new ButtonCustomModel(true));
ButtonCustomModel:
public class ButtonModel implements javax.swing.ButtonModel {
protected boolean state;
public ButtonModel(boolean state)
{
this.state = state;
}
#Override
public boolean isSelected() {
return state;
}
#Override
public boolean isEnabled() {
return true;
}
// other methods of ButtonModel-interface
[...]
}
I cannot use setEnabled(false), because I need to set the background- and foregroundcolor
This is probably just purely a personal thing, but I have a distinct dislike or UI's which don't conform to establish norms and user expectations.
So, when a button shouldn't be interacted with, it should be disabled. This is a convention that a user understands immediately.
I change the background-color and foreground-color for the evaluation-radiobuttons and -checkboxes.
Okay, so you want to decorate the buttons in some way, fair enough
It is clear from context that they are not meant to be checked by the user
To you perhaps, I'd probably be madly trying to click it, but I'm just that kind of user ;)
Okay, so with just a little but of paying around with the UIManager's default values, it's possible to take more control over how some elements are rendered, for example...
UIManager.put("RadioButton.disabledText", Color.BLUE);
JRadioButton rb = new JRadioButton("Test");
rb.setOpaque(true);
rb.setBackground(Color.RED);
rb.setForeground(Color.BLUE);
rb.setEnabled(false);
add(rb);
UIManager.put("CheckBox.disabledText", Color.RED);
JCheckBox cb = new JCheckBox("Test");
cb.setOpaque(true);
cb.setBackground(Color.BLUE);
cb.setForeground(Color.RED);
cb.setEnabled(false);
add(cb);
Now, this is just a quick hack.
For me, I might consider doing something different to highlight the correct answer, maybe fading or removing the other questions or use a LineBorder to highlight the correct answer or use a JLabel and nice big green tick or red cross, as some simple idea off the top of my head.

Minesweeper flags java

I'm pretty new in programming, but i need to program the game Minesweeper.
basically the game is running, but there are some parts that wont work at all.
The first problem are the flags. My Minesweeper is able to set flag by right clicking on a field, but everytime i do a left-click on a field with a flag, the field will override the flag.
Field after a right click
Flagged field after a left click
Is there any way to set the flag "absolute" or final or something?
Here is the code:
#Override
public void mouseClicked(MouseEvent arg0) {
if (SwingUtilities.isRightMouseButton(arg0)) {
setFlag();
} else if (SwingUtilities.isLeftMouseButton(arg0)) {
checkMine();
}
public void setFlag() {
button.setEnabled(false);
button.setText(flag);
button.setBackground(Color.LIGHT_GRAY);
}
public void checkMine() {
button.setEnabled(false);
display();
check = false;
if (value == 0)
log.emptyCells();
if (value == -1)
log.fail();
if (value == -3)
log.lucky();
}
I hope that someone here can help me.
tanks :)
When you are using methods with button, you are never specifying which button you are disabling. I recommend adding a JButton parameter to your methods so you can change them.
Also, the check boolean is never initialized as a boolean, unless it's an instance variable you are using, in which case you need to edit your post to include your instance variables.

Cursor Change by MouseMove Event doesn't work

i've got some problem with my Mouse Cursor. I set it inside my MouseMotion Event of a JPanel with this.setCursor(), but it dosen't changed.
After getting out ouf the Window for example on my Desktop and go back inside , the cursor will be changed by any motion.
The Code of the mouse Event of the JPanel is this:
public void mouseMoved(MouseEvent e) {
this.requestFocusInWindow();
this.requestFocus();
this.cL.doMouseMoved(e);
}
The Code of the Method doMouseMoved is this:
public void doMouseMoved(MouseEvent e) {
this.lastMouseEvent = e;
this.sList.setCurrentElements(e.getPoint());
this.setMovedCursor(e);
}
An finally this is the code of the method setMovedCursor:
public void setMovedCursor(MouseEvent e) {
java.awt.Cursor cu = new java.awt.Cursor(java.awt.Cursor.SW_RESIZE_CURSOR);
view.setCursor(cu);
}
(I know that this isn't the best way)
I hope everyone can help me.
Sorry for any mistakes, it's my first post at stackoverflow.
if (sList.getCurrentShapeType() == "rec") {
Not sure if it will fix your problem but don't use "==" to compare objects.
Instead you should be using the equals(...) method.
if ("rec".equals(sList.getCurrentShapeType()) {
Note: I changed the order of the test so you don't have to worry about the getCurrentShapeType() method returning a null value.
else if (k.getBorderByPoint(e.getPoint()) == 4)
Also, I don't know what your getBorderByPoint() method does but why are you comparing it to an integer value. We have no idea what "4" means. Don't use "magic numbers. Instead create variables like: CURSOR_NORTH. Or better yet why not just return the cursor from that method so you don't have to check the value twice.

Get GWT DialogBox absolute position - onLoad/onAttach/show do not helps

I am stuck in getting an absolute position of DialogBox. I know it is the common problem (and strange workaround) for PopupPanel (which is parent to DialogBox) to set it, but what if I want to get it, what is the exact moment when the box attached to DOM? Neither overriding show nor onAttach nor show does not help:
class MyDialog extends DialogBox {
public MyDialog(. . .) {
ComplexPanel vert = new VerticalPanel();
vert.add("Test");
vert.add(new Button("Close", new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
MyDialog.this.hide();
}
}));
setWidget(vert);
this.addAttachHandler(new AttachEvent.Handler() {
#Override
public void onAttachOrDetach(AttachEvent event) {
if (event.isAttached()) Log.debug("attach:"+MyDialog.this.getAbsoluteLeft() +";"+
MyDialog.this.getAbsoluteTop());
}
});
}
#Override
protected void onLoad() {
super.onLoad();
Log.debug("load:"+this.getAbsoluteLeft() +";"+this.getAbsoluteTop());
}
#Override
public void show() {
super.show();
Log.debug("show:"+this.getAbsoluteLeft() +";"+this.getAbsoluteTop());
}
}
So when I call new MyDialog().show();, all this lines do log 0;0, however dialog is positioned in center of a page. But what I want is the sum of the chain of offsetParent positions. (And they are 0 in these moments even in JavaScript, if use JSNI to check this)
Again, setPopupPositionAndShow allows to set position but not get it :(
Finally, I've got this to work:
#Override
public void setPopupPosition(int left, int top) {
super.setPopupPosition(left, top);
if (this.isAttached()) Log.debug("setPos:"+this.getAbsoluteLeft() +";"+this.getAbsoluteTop());
}
It gets the proper position and I hope it is the right way to do it and setPopupPosition is called every time. You will even call it manually when using setPopupPositionAndShow.
I think it will be wise to let this question stay at SO "for future generations".
Upd. If you plan to call center(...) or some similar method of your dialog, be aware that setPopupPosition will be called twice or more times (may be first time with 0, 0), even if you'll check if it isAttached(). Add some additional check to ensure that positions are correct in current call.

Can Swing tell me if there is an active tooltip?

Is there an elegantish way in Swing to find out if there are any tooltips currently being displayed in my frame?
I'm using custom tooltips, so it would be very easy to set a flag in my createToolTip() method, but I can't see a way to find out when the tooltip is gone.
ToolTipManager has a nice flag for this, tipShowing, but of course it's private and they don't seem to offer a way to get to it. hideWindow() doesn't call out to the tooltip component (that I can tell), so I don't see a way there.
Anyone have any good ideas?
Update: I went with reflection. You can see the code here:
private boolean isToolTipVisible() {
// Going to do some nasty reflection to get at this private field. Don't try this at home!
ToolTipManager ttManager = ToolTipManager.sharedInstance();
try {
Field f = ttManager.getClass().getDeclaredField("tipShowing");
f.setAccessible(true);
boolean tipShowing = f.getBoolean(ttManager);
return tipShowing;
} catch (Exception e) {
// We'll keep silent about this for now, but obviously we don't want to hit this
// e.printStackTrace();
return false;
}
}
It appears that the isEnabled() property of the hideTipAction is directly tied to the tipShowing boolean. You could try this:
public boolean isTooltipShowing(JComponent component) {
AbstractAction hideTipAction = (AbstractAction) component.getActionMap().get("hideTip");
return hideTipAction.isEnabled();
}
You probably want to do some sanity checking for nulls, etc. But this should get you pretty close.
EDIT, to your responses:
Short of some ugly reflection code, I don't think you have much choice. You cannot subclass ToolTipManager because of the package private constructor, and the showTipWindow() and hideTipWindow() are also package private, so the Adapter pattern is out as well.
It looks like that is going to require looping over all of the components to see if they have a tooltip. I'm looking for a global value. It may be that a loop is doable, but it seems inefficient.
That's too bad. After an internal discussion, "ugly reflection" was what we came up with as well, but I was hoping someone out there had a better idea.
Since you already have your own createToolTip(), maybe you can try something like this :)
public JToolTip createToolTip() {
JToolTip tip = super.createToolTip();
tip.addAncestorListener( new AncestorListener() {
public void ancestorAdded( AncestorEvent event ) {
System.out.println( "I'm Visible!..." );
}
public void ancestorRemoved( AncestorEvent event ) {
System.out.println( "...now I'm not." );
}
public void ancestorMoved( AncestorEvent event ) {
// ignore
}
} );
return tip;
}

Categories