JavaFX KeyCode for percent (%) - javafx

I want to detect when certain keys are pressed. I can't seem to find a KeyCode for the percent (%) sign. I have scoured the JavaFX 8 JavaDoc, and there is no Enum constant for PERCENTlike I would expect. Google was not helpful either. Is there something special about % that I don't know about?
#FXML
private void keyPressed(KeyEvent evt) {
if (evt.getCode().isDigitKey() && !evt.isShiftDown()) {
String number = evt.getText();
numberAction(number);
}
if (evt.getCode().equals(KeyCode.DECIMAL)) {
decimalAction();
}
if (evt.getCode().equals(KeyCode.PERCENT)) {
percentAction();
}
}
The Enum KeyCode.PERCENT does not exist.

Rather than using the keyPressed event, use the keyTyped event and use KeyEvent.getCharacter to get the result independent from keyboard layout:
#FXML
private void keyTyped(KeyEvent evt) {
...
if ("%".equals(evt.getCharacter())) {
percentAction();
}
}
(You need to modify your fxml file of course.)

Did u try this?
YOUR_CONTROLLER.setOnKeyPressed(event ->{
if((event.getCode() == KeyCode.DIGIT5) && event.isShiftDown())
System.out.println("It's work");
});
And yes, u can't find KeyCode for this symbol because to write it you should to press more then 1 key (:
UPDATE:
You also can try this:
YOUR_CONTROLLER.setOnKeyPressed(event ->{
if((event.getText().equals("%"))
System.out.println("It's work");
});

Related

change text based on button-click

I am using Unity3d
I've tried to track where the problem comes from and had no success. The text update in "Guess" occurs properly when done by key press, but no by clicking the button (both log in an exception).
The code:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class NumberWizard : MonoBehaviour
{
public Text guessText;
int min;
int max;
int guess;
public void Higher ()
{
min = guess;
NextGuess ();
}
public void Lower ()
{
max = guess;
NextGuess ();
}
public void Correct ()
{
print ("I won!");
StartGame ();
}
private void StartGame ()
{
min = 1;
max = 1000;
guess = 500;
guessText.text = guess.ToString();
print (guess);
}
private void NextGuess ()
{
guess = (max + min) / 2;
guessText.text = guess.ToString();
print (guess);
}
// Use this for initialization
void Start ()
{
StartGame ();
}
// Update is called once per frame
void Update ()
{
if (Input.GetKeyDown (KeyCode.UpArrow)) {
Higher ();
} else if (Input.GetKeyDown (KeyCode.DownArrow)) {
Lower ();
} else if (Input.GetKeyDown (KeyCode.Return)) {
Correct ();
}
}
}
By the way, I've put the buttons on another controller called "LevelManager". I've added [RequireComponent(typeof(LevelManager))] above class declaration, but it didn't work.
Basically, it says that in guessText.text = guess.ToString(); object is not set to an instance, but I've set in Unity3d that the particular text is referenced and that it should use NumberWizard.cs
When you create this script it need to be attached to a GameObject. As you have done the coding it should be attached to an Empty gameObject. Then when you select the script from editor your public variable Text guessText will be available on the edior, Now you have to drag and drop the GUIText you have created on to the guessText property.
The error says that you have to initialize the variable, whether by doing a "new" or asingning it to a ingame drag'n'drop object as Dinal says.

Delete JavaFX table row with delete key

Is there a way to delete selected table row using keyboard delete key?
Is there any example with this implementation?
Sure you can. You only have to register an EventHandler and listen to the specific KeyCode. Following example is for TreeTableView but should be applyable for all TableViews.
treeTableView.setOnKeyPressed( new EventHandler<KeyEvent>()
{
#Override
public void handle( final KeyEvent keyEvent )
{
final TreeItem<YourObject> selectedItem = treeTableView.getSelectionModel().getSelectedItem();
if ( selectedItem != null )
{
if ( keyEvent.getCode().equals( KeyCode.DELETE ) )
{
//Delete or whatever you like:
presenter.onEntityDeleteAction( selectedItem );
}
//... other keyevents
}
}
} );
After trying a lot I managed to intercept and handle (with my application logic) the Delete key (Del or Canc, as you prefer to call it).
Thanks to some debugging I understand that the Delete key is identified with the Unicode code: \u007F.
So, the moment I type the key, I read the character and compare it with this code.
Here is a piece of my code that has nothing to do with table views but I used it for a TextField.
The important thing is the reasoning.
#FXML
public void myKeyListener(KeyEvent keyEvent) {
//Matches and manage TAB, Enter and Delete buttons
if ((keyEvent.getCharacter().equals("\t") ||
keyEvent.getCharacter().equals("\r") ||
keyEvent.getCharacter().equals("\u007F") //<-- **THIS** is the important one! *****
)) {
//My / your application logic
keyEvent.consume(); //The documentation says: "Marks this Event as consumed. This stops its further propagation."
return;
}
//Other logic...
//Entered only to have test outputs
System.out.println("getCode: " + keyEvent.getCode());
System.out.println("getCharacter: " + keyEvent.getCharacter());
System.out.println("getText: " + keyEvent.getText());
System.out.println("isMetaDown: " + keyEvent.isMetaDown());
}
Outputs:
getCode: UNDEFINED
getCharacter: ⍰
getText:
isMetaDown: false
I hope it can be useful to someone else. 🤞
P.S. I'm using Windows 10 with italian keyboard layout. In case it's relevant.

OnCollisionEnter2D isn't working and I don't know why

I'm new to Unity and c# and I'm trying to get the basics down but I seem to be having some trouble with the collision. I want to get a falling object to destroy when it collides with another object that is stationary. All of the objects are set to Box Collider 2D in Unity and after hours of searching I can't seem to figure out what's wrong with it. Any help would be much appreciated!
using UnityEngine;
using System.Collections;
public class Destroy : MonoBehaviour {
// Use this for initialization
void Start () {
transform.position = new Vector2 (0, -10);
Debug.Log ("Game Start");
}
// Update is called once per frame
void Update () {
}
void OnCollisionEnter2D(Collision2D col)
{
if (col.gameObject.tag == "Target") //|| (col.gameObject.tag == "fallingCube2"))
{
Debug.Log ("There has been a collision!");
Destroy (col.gameObject);
}
else
if (col.gameObject.tag == "otherTarget")
{
Debug.Log ("There has been a collision!");
Destroy (col.gameObject);
}
}
}
Make sure that the Tag is the same (care with uppercase), and use col.tag == "Target".
The GameObject must have and BoxCollider2D or other Collider2D with the property isTrigger to false.
I always use OnTriggerEnter2D(Collider2D col) because I dont want that my pj stops falling or whatever

QlineEdit with some default text for which cursor should not be moved?

In QT, a created lineEdit shows a text using the setText() method.
But the cursor is movable for the default text. I want the cursor should not be movable for the default text.
My lineEdit type has been set as password. Hence the default text('Password') is also displayed as '********'. Whenever user types the type has to be changed as password and when there is no text or until the user have not typed any text, the lineEdit should display the plain text 'password'
Any idea to fix the above two issues?
In the constructor put
ui->lineEdit->setPlaceholderText("password");
ui->lineEdit->setReadOnly(1);
And in on_lineEdit_selectionChanged() SLOT, put
ui->lineEdit->setText("");
ui->lineEdit->setEchoMode(QLineEdit::Password);
ui->lineEdit->setReadOnly(0);
I noticed this question has tag pyqt so I'll put an actual answer related to that tag for those actually looking for a python way instead of c++.
self.searchEditText = QtGui.QLineEdit()
self.searchEditText.setPlaceholderText("Search for word")
I managed to do what you want by deriving a class from QLineEdit as per following..
Constructor..
QCustomLineEdit::QCustomLineEdit(QWidget *parent) :
QLineEdit(parent)
{
connect(this, SIGNAL(textChanged(QString)), this, SLOT(onTextChanged(QString)));
connect(this, SIGNAL(cursorPositionChanged(int,int)), this, SLOT(onCursorPositionChanged(int,int)));
setEchoMode(QLineEdit::Password); // Echo mode in your case..
m_echoMode = echoMode(); // Member variable to store original echo mode..
m_placeHolderText = "Password"; // Member variable..
m_isPlaceHolderActive = true; // Member varible..
// Default case..
setPlaceholderText("");
setStyleSheet("QCustomLineEdit{color: gray;}");
setEchoMode(QLineEdit::Normal);
setText(__placeHolderText);
}
Override keyPressEvent..
void QCustomLineEdit::keyPressEvent(QKeyEvent *e)
{
if(m_isPlaceHolderActive)
{
if(e->key() == Qt::Key_Delete || e->key() == Qt::Key_Backspace)
e->accept();
else
QLineEdit::keyPressEvent(e);
return;
}
QLineEdit::keyPressEvent(e);
}
Cursor position change event..
void QCustomLineEdit::onCursorPositionChanged(int /*oldPos*/, int newPos)
{
if(m_isPlaceHolderActive)
{
if(newPos != 0)
setCursorPosition(0);
}
}
Text change event..
void QCustomLineEdit::onTextChanged(const QString &text)
{
if(m_isPlaceHolderActive)
{
if(text.compare(m_placeHolderText) != 0)
{
m_isPlaceHolderActive = false;
// Remove the 'placeHolderText' from 'text' itself..
QString temp = text;
temp = temp.mid(0, text.lastIndexOf(m_placeHolderText));
setStyleSheet("QCustomLineEdit{color: black;}");
setEchoMode(m_echoMode);
setText(temp);
}
else
{
setEchoMode(QLineEdit::Normal);
setText(m_placeHolderText);
setStyleSheet("QCustomLineEdit{color: gray;}");
setCursorPosition(0);
}
}
else
{
if(text.isEmpty())
{
m_isPlaceHolderActive = true;
setStyleSheet("QCustomLineEdit{color: gray;}");
setEchoMode(QLineEdit::Normal);
setText(m_placeHolderText);
}
}
}
I have written it very hastily to just show you. Test it yourself and feel free to point any mistake(s) or optimization(s). Hope this helps.
For question 1, in Qt 5.0 and higher, setPlaceholderText does what you want. https://codereview.qt-project.org/#change,45326

UIImagePickerController Crashing Monotouch

I am trying to write an application, but it is constantly crashing when using the uiimagepickercontroller. I thought that it might be because I was not disposing of the picker after each use, but it will often freeze up on first run as well. Usually I'll take a picture and it just freezes, never asking to "use" the picture.
Do you have any suggestions? Here is my code. Has anyone gotten this to work?
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
myPicker = new UIImagePickerController();
myPicker.Delegate = new myPickerDelegate(this);
myAlbumButton.Clicked += delegate {
if(UIImagePickerController.IsSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary)){
myPicker.SourceType = UIImagePickerControllerSourceType.PhotoLibrary;
myPicker.AllowsEditing = true;
this.PresentModalViewController (myPicker, true);
}else{
Console.WriteLine("cannot get album");
}
};
myCameraButton.Clicked += delegate {
if(UIImagePickerController.IsSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)){
myPicker.SourceType = UIImagePickerControllerSourceType.Camera;
//myPicker.AllowsEditing = true;
this.PresentModalViewController (myPicker, true);
}else{
Console.WriteLine("cannot get camera");
}
};
}
private class myPickerDelegate : UIImagePickerControllerDelegate
{
private TestView _vc;
public myPickerDelegate ( TestView controller):base()
{
_vc = controller;
}
public override void FinishedPickingImage (UIImagePickerController myPicker, UIImage image, NSDictionary editingInfo)
{
// TODO: Implement - see: http://go-mono.com/docs/index.aspx?link=T%3aMonoTouch.Foundation.ModelAttribute
_vc.myImageView.Image = image;
myPicker.DismissModalViewControllerAnimated(true);
}
}
Try to call your event handlers code from the main thread by using BeginInvokeOnMainThread().
So my issue was very similar.
Instead of having a delegate class, I had the delegates inline for the picker.
For some reason the app froze every time after talking the image, not stopping in any breakpoint after that.
The solution that worked for me was to use this book:
http://www.scribd.com/doc/33770921/Professional-iPhone-Programming-with-MonoTouch-and-NET-C

Resources