Key listener java - number limitation - java

I've got an app in JFrame. Here is part of the code:
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String input = text.getText();
int number = Integer.parseInt(text.getText());
if(number>0)
{
for(int i=0; i<liczba; i++)
{
new NewWindow();
}
}
}
});
This action creates new windows in app where number of windows depend on number we've inputted. I need to make sure it IS a number (not a letter or something). I also know the key listener must be used and the symbol inputted has to be between some values of ASCII which represent numbers. But I don't know how to do this exackly. Any solutions?

I also know the key listener must be used
No a KeyListener does not need to be used. That is probably the oldest solution and was used in AWT. Swing has newer and better API's which you should be using.
You could use a JSpinner, JFormattedTextField or a DocumentFilter.
Read the Swing Tutorial. You should check out sections on:
How to Use a Spinner
How to use Formatted Text Fields
How to Write a DocumentFilter
Any one of the above is a better solution than using a KeyListener.

Related

How to ensure that a JTextField input meets requirements?

So I'm making a module that has three JTextField windows corresponding for 24 bit RGB color values "R", "G" and "B" with buttons for decrement/increment. The module is supposed to take these values and display the color. I did that and it works, but I need to ensure some details about the inputs and I don't know how to. These details are:
if you enter a value outside of 0 and 255 it will be treated as 0
if you click a decrement button when the value is 0 it won't drop it to -1
if you click an increment button when the value is 255 it won't rise to 256. I have no idea how to do it. I tried to google it but
I can't find what I need. I'd appreciate some guidance
EDIT:
I tried to add some if statements to the ActionPerformed method but all it does is returns a whole bunch of errors when I run the module and try the value out of range
EDIT2: for example, I had this but it doesn't work :
#Override
public void actionPerformed(ActionEvent e) {
String r,g,b;
if (e.getSource() == tf1) {
r = tf1.getText();
this.r =Integer.parseInt(r);
if (this.r < 0 && this.r > 255)
this.r =0;
color(); }
I have nothing for my buttons because I have completely no idea how to
This sounds like you might need some data validation from your input sources. We can't see your code, but one way to validate would be have your getters/setters generated for your variables. (Depending on the editor you have, these can be generated rather quickly). Within the values setter - you should be able to do some data validation.
If you post some code, you might get more meaningful feedback.
More on getters and setters in Java: https://www.codejava.net/coding/java-getter-and-setter-tutorial-from-basics-to-best-practices
EDIT:
Now that you've posted code. Change the && to || and that should take care of your issue.
It is still better to data validate this with a getter/setter.

Java Swing: KeyBinding for KEY_TYPED event

I've been trying to learn keybinds by rewriting problems from my book that I've previously solved using KeyListener. The problem that I'm struggling to solve using keybinds requires me to record a message that's been typed and to display it on the panel.
The way it was solved using KeyListener is simply by recording characters with unicodes using the keyTyped() method and reading modifier/non-Unicode keys with keyPressed. If KeyEvent.VK_ENTER matches the keycode from the keyevent, then it displays the string on the panel.
~~~~~~~~
I thought that it can be solved in a similar way with KeyBinds. It says in the KeyEvent docs that KeyEvent.KEY_TYPED is fired every time a character is entered. I assumed that it meant every character with a corresponding Unicode being typed like how it works in KeyListener.
Later on, I realized that I have no idea how to retrieve the character since the Oracle tutorial on KeyBinds says that the KeyEvent is consumed when actionPerformed() is invoked.
This is the code that I THOUGHT would enable me to record typed keys to a StringBuilder using KeyBindings:
getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.KEY_TYPED, 0), "recordTypedKey");
getActionMap().put("recordTypedKey", addCharToString);
Is there a way to obtain the characters that would invoke KeyListener's keyTyped() method besides adding a key to every one of them and using a separate Action event to record them?
Is there a way to obtain the characters that would invoke KeyListener's keyTyped() method besides adding a key to every one of them and using a separate Action event to record them?
I do not believe there is a global KeyStroke you can pass to the InputMap that will work similar to a KeyListener, as KeyBindings work on an individual key basis. You can however create a single Action and bind keys to it by looping over the char values you wish to process - in the ActionListener implementation you can obtain the value of the key via getActionCommand. For example to deal with a-z:
AbstractAction action = new AbstractAction(){
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(e.getActionCommand());
}
};
//loop over the ascii char values
for ( char a = 'A'; a <= 'Z'; a++ ){
panel.getInputMap().put(KeyStroke.getKeyStroke(Character.toString(a)), "recordTypedKey");
}
panel.getActionMap().put("recordTypedKey", action);
You can add modifiers if needed...for example to deal with the shift key (eg upper case),
panel.getInputMap().put(KeyStroke.getKeyStroke("shift " + Character.toString(a)), "recordTypedKey");

How to convert string variable to KeyEvent - General approach

I am pretty new to Java and I have one question that is bugging me for days.
I am building small app where you press certain key on keyboard and then it does something. Generally - it will play drums
Here's the example.
private void KeyListener(java.awt.event.KeyEvent evt)
switch (evt.getKeyCode()) {
case KeyEvent.VK_Q: new AePlayWave("kits/acoustic/Bass.wav").start();;
break;
case KeyEvent.VK_W: new AePlayWave("kits/acoustic/Bass.wav").start();;
break;
}
This is clear. You press Q button and then you get the bass drum kick . I just copied the part of the code, there are more elements like snare, cymbals, etc.
I have built the CONFIGURE KEYS option which takes Strings and passes them to combo boxes. I have created combo boxes with all letters on keyboard so the user can change the layout if default is not working for him/her.
I have a public class with a variable:
Public static SnareKey1 = "Q";
When you change the combo box then SnareKey1 is changed to let''s say - Y (or whatever). That works BUT ----
My question is: How can I transfer this SnareKey1 to KeyEvent. Am I doing this with correct approach or I need a different one?
I have solved this!
You just can't use variables in CASE (switch statement). You need constant expression.
I have resolved this with IF/ELSE statement.
Basically, I added KeyListener to the main form and wrote IF evt.keycode = snareKey.hashcode then play the sound.

Getting the sum from gwt table element

I have a table written in GWT from a List list. What i want it is to obtain the sum of a certain group of elements.
The problem with this, it is that the value I want to do the sum with its calculated, and thus not obtainable unless you calculate it before generating the List.
I was wondering if it was somehow possible to achieve this through DOM manipulation. And if so, how?.
I will show you an example:
DataA DataB DataC DataD
---------------------------------
aaaaa bbbbb ccccc 12
aaaa1 bbbb1 cccc1 15
aaa11 bbb11 ccc11 17
I want to get the sum of "DataD" column, but i dont know how can i do it.
Thank you in advance for your time,
Kind regards,
Elaborate: DataD column value it is calculated and the value comes from another system and its placed into the table through a third party program; thus i cannot get its value and use it into a sum to get the value i want.
You should be able to add some event handler to the table's widget so that whenever data is added/changed in the widget, you adjust the total. Please give more information about what widgets you are using to represent the table.
EDIT:
now that we know you are using an HTMLLayoutContainer, I assume DataD is being poopulated at a place beyond your controll in code. What you can do is add event handlers to handle the add remove etc events. For example, you could do something like below:
//Your container
HtmlLayoutContainer c = new HtmlLayoutContainer(templates.getTemplate());
c.addAddHandler(new AddEvent.AddHandler() {
#Override
public void onAdd(AddEvent event) {
//Do proper exception handling, check if it is the right widget for dataD, do the needed calculations etc
sum += Double.parseDouble(((HTML)event.getWidget()).getHTML());
}
});
c.addRemoveHandler(new RemoveEvent.RemoveHandler() {
#Override
public void onRemove(RemoveEvent event) {
//handle all conditions like in onAdd in AddHandler above
sum -= Double.parseDouble(((HTML)event.getWidget()).getHTML());
}
});
You can look into the API to see what exactl events match your needs best (http://dev.sencha.com/deploy/gxt-3.0.0/javadoc/gxt/com/sencha/gxt/widget/core/client/container/HtmlLayoutContainer.html)

Checking JTextField Characters

I have a program I've written for my kids to practice basic arithmetic. There is a JTextField on a JFrame where the student keys in the answer to a given math problem (like 8+8, they key in 16, Enter). This field accepts only integer values as entries by way of a DocumentFilter.
That part works just fine. What I want to do with this is to avoid having the user have to hit the enter key. Ideally, when the user keys in the first number (1), a check is done to see if 1 == 16. If not, nothing happens. When they subsequently type the 6, the text field displays the number 16. I want to run a check to verify if 16 == 16, and then handle the entry as if the user had also hit the Enter key.
txtAnswer.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_ENTER) {
respondToAnswer(isTimed);
} else {
/* Check if the correct answer has been entered */
System.out.println(txtAnswer.getText());
//int userAnswer = Integer.parseInt(txtAnswer.getText());
//if (userAnswer == correctAnswer {
// respondToAnswer(isTimed);
//}
}
};
});
This code isn't quite working. It's as if it is one character behind. What I mean by that is when the user hits the '1' key (in my 8+8=16 example), the console output is an empty string. When they hit the '6' key, the output is '1'. If they then hit another integer key, the output is '16'. It's always one digit behind. Because of this, I cannot capture the entire contents of the text field to see if it matches the correct answer.
Anyone see what I am missing?
Thanks!
Use a DocumentListener for that instead of a KeyListener. In all three events, you will have access to the actual text content.
To listen for the Enter on JTextField, us an ActionListener
Side note: you should almost never need a KeyListener. On JTextComponent, always rely on a DocumentListener. For all the others, use appropriate Swing Key bindings. KeyListener is really a low level API.
You should use DocumentListener for this purpose. keyPressed is probably fired before the text in the field is updated.
See How to Write a Document Listener for details and examples.

Categories

Resources