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.
Related
I'm a java Beginner and I've created a program where you can type in some food in a TableView and the details of the respective food you can type in a GripPane. One of the Details you have to type in is the quantity of the food, and another is the Calories per piece. Now I would like to create a button and a field. Or Maybe just a field that shows all calories of the food in the Table view. So it should multiplicate the quantity with the calories, for every food and add them all together. For a Total of Calories. Now I have no idea how to do that. Could somebody help me with step-by-step instructions? Not sure if it makes sense to add some code to the program. By the way, I use Eclipse on Windows and SceneBuilder. Thanks for every help.
Cheers Blarg
The first piece of advice from my side would be to try writing some code on your own! That way you learn and you wouldn't need to copy and paste somebody else's code.
And secondly, this is how I would approach it:
Create the fields as you described below in the Scene Builder and give them all id (names) so that we can access them in our controller (I am supposing you know how that works).
Add a button so that the user can click to perform the calculation
When the button is clicked, you can get all the information from each TextBox and create a Food Object with all the information. Performing the calculation is a rather simple task that can be done by converting the data received from the TextBoxes into numbers and multiplying
public void addFoodItemIntoTable()
{
...
String quantityOfFoodStr = quantityTextBox.getText();
int quantityOfFood = Integer.parseInt(quantityOfFoodStr);
String caloriesOfFoodStr = caloriesTextBox.getText();
double caloriesOfFood = Double.parseDouble(caloriesOfFoodStr);
double total = quantityOfFood * caloriesOfFood;
...
}
After adding all the elements in your TableView (Check this). You can easily get the total of the field by iterating all the elements of your table and adding them into a variable.
Example:
double total = 0;
for(Food currentFood : foodTable.getItems())
{
total = total + currentFood.getTotalCalculation(); // The naming should not be correct... Change it to whatever you find suitable
}
Good luck!
I am trying to create a simple Blackjack game in Java. I have a menu with possible integer options from 1-4. If the user inputs an integer greater than 4, my IF statement needs to print "invalid integer" and then restart the game. If the user inputs a negative value, my ELSE-IF statement needs to do the same thing.
However, the statements will only work once, so I can't get "invalid integer" to print if I input values below 0 and values greater than 4 multiple times/back-to-back.
[Redacted]
Any help is appreciated.
If you have defined scnr like this:
Scanner scnr = new Scanner(System.in);
I suggest you do a simple switch case statement with a default clause.
switch (userOpt) {
case 1:
// Option 1 logic...
case 2:
// Option 2 logic...
case 3:
// Option 3 logic...
case 4:
// Option 4 logic...
default:
// Handling invalid input...
}
It's really confusing in the way you've written the code.
I.e how does case 1 involve get another card?
Is all the code written in a main function? How about you make a class called blackjack in which you have different methods for getCard(), holdHand() etc. and make a class variable which holds the hand and also gamecount and wins for dealer/player. Would be much easier to understand your code.
Then you can try you code in your main inside the code.
Something like;
public BlackJack {
**class variables such as hand, player wins etc..**
**methods here**
**main method to try your code**
}
I hope you get what I'm suggesting, I know it might feel like a lot of work to do now when you've written your code but this would help you and anyone who reads your code.
INTRODUCTION:
I am having some trouble enforcing validation to a pair of EditText values in an Android project. The language is Java. android:inputType="number" is set. Both views are empty, by default.
For example, the validation rule is that editTextA and editTextB cannot both be zero. Ideally, the validation should be performed when the user finishes input in either view.
UPDATED QUESTION:
Here's another example. Values of editTextA and editTextB should sum up to 5 max.
Using TextWatcher seems to work okay but it's far from perfect. I think the best way would be to somehow be able to restrict user input on one control based on the current value of the other. Let's say that onCreate contains the following code:
editTextA.setFilters(new InputFilter[]{ new InputFilterMinMax("0", "5")});
editTextB.setFilters(new InputFilter[]{ new InputFilterMinMax("0", "5")});
where InputFilterMinMax is a class that implements InputFilter as per Is there a way to define a min and max value for EditText in Android?
Now let's assume value of editTextA becomes 3. The max filter value of editTextB should now be 2 instead of 5.
The question is can this be applied on-the-fly?
PART OF ORIGINAL QUESTION:
Problem 1: I tried to set a EditorActionListener but there are just too may ways a control can lose focus and I can't get the validation code to work on all cases. I've tried:
if (actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_NEXT || actionId = EditorInfo.IME_ACTION_PREVIOUS) {
// get values of A and B
return (valueA+valueB>0);
}
return false;
but doesn't seem to work when the user clicks directly on another control, for example.
Problem 2: The above approach doesn't seem to work in a consistent way especially when I am trying to set an error, too. Where the setError() should be called in the action listener?
Overall, the above approach seems clumsy. Is there any other way to perform such validation?
How would I send text to the computer (like a keyboard) via a Java class?
I have considered using the Robot class to press and release each key, but that would be tedious and there is no way to get the KeyCode from a char.
No, there is also a soft way (well, on Windows it works at least ;-)):
private static void outputString(Robot robot,String str)
{
Toolkit toolkit = Toolkit.getDefaultToolkit();
boolean numlockOn = toolkit.getLockingKeyState(KeyEvent.VK_NUM_LOCK);
int[] keyz=
{
KeyEvent.VK_NUMPAD0,
KeyEvent.VK_NUMPAD1,
KeyEvent.VK_NUMPAD2,
KeyEvent.VK_NUMPAD3,
KeyEvent.VK_NUMPAD4,
KeyEvent.VK_NUMPAD5,
KeyEvent.VK_NUMPAD6,
KeyEvent.VK_NUMPAD7,
KeyEvent.VK_NUMPAD8,
KeyEvent.VK_NUMPAD9
};
if(!numlockOn)
{
robot.keyPress(KeyEvent.VK_NUM_LOCK);
}
for(int i=0;i<str.length();i++)
{
int ch=(int)str.charAt(i);
String chStr=""+ch;
if(ch <= 999)
{
chStr="0"+chStr;
}
robot.keyPress(KeyEvent.VK_ALT);
for(int c=0;c<chStr.length();c++)
{
int iKey=(int)(chStr.charAt(c)-'0');
robot.keyPress(keyz[iKey]);
robot.keyRelease(keyz[iKey]);
}
robot.keyRelease(KeyEvent.VK_ALT);
}
if(!numlockOn)
{
robot.keyPress(KeyEvent.VK_NUM_LOCK);
}
}
Try use this :
http://javaprogrammingforums.com/java-se-api-tutorials/59-how-sendkeys-application-java-using-robot-class.html
Use a GUI testing framework (even if you do not use it for testing). I recommend FEST. In FEST you can search for GUI elements and automate all kinds of user interactions including entering text.
For example once you have a text field fixture (the FEST term for a wrapper that lets you control the component), you can do
JTextComponentFixture fixture = ...;
fixture.enterText("Some text");
#JavaCoder-1337 Not exactly...
Although some switch-case (hard way?) is still needed to handle some (special) characters, most of the characters can be handled fairly easily.
How much you need depends on your target audience, but whatever the case, you can handle it through a combination of:
AWTKeyStroke.getAWTKeyStroke(char yourChar).getKeyCode(); - Which
handles the most basic ones; a-zA-Z are translated to they'r base
(a-z) keyEvents, and a few other chars are also handled similarly (base key only, no modifiers thus no casing is applied).
As you can imagine, this method is particularly effective for simplifying English handling, since the language makes little use of accented letters compared to many others.
Normalizer.normalize(String textToNormalize, Form.NFD); - Which decomposes most composed (accented) characters, like áàãâä,éèêë,íìîï,etc, and they'r uppercase equivalents, to they'r base elements. Example: á (224) becomes a (97) followed by ´ [769].
If your send(String text) method is able to send accents, a simple swap of the accent (in the example it's VK_DEAD_ACUTE) and it's letter, so that they get to proper send order, and you will get the desired á output. Thus eliminating the need for an á filter.
Combined with the first simplification, for this example, that makes 1/3 [´] instead of 3/3 [a,á,´] switch-case needed!
These are only a few of many simplifications that can be done to shorten that dreadfully long switch-case method that is (unwisely) suggested by many fellow programmers.
For example, you can easily handle casing by detecting if the character to be sent is uppercase, and then detecting the current capslock state to invert the casing operation, if needed:
boolean useShift = Character.isUpperCase(c);
useShift = Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_CAPS_LOCK) ? !useShift : useShift;
if (useShift) {
keyPress(KeyEvent.VK_SHIFT);
sendChar(aChar);
keyRelease(KeyEvent.VK_SHIFT);
} else {
sendChar(aChar);
}
Another option (the one that I use), which is even simpler, is to simply code a macro in a tool/language that is (far) more suited for this kind of operation (I use and recommend AutoHotKey), and simply call it's execution from Java:
Runtime rt = Runtime.getRuntime();
//"Hello World!" is a command-line param, forwarded to the ahk script as it's text-to-send.
rt.exec(".../MyJavaBot/sendString.ahk \"Hello World!\"");
(using netbeans and java)
I have the following
1 text field named input 1 (named x5)
1 text field named input 2 (named plus10)
1 text field named input 3 (named plus5perc)
1 answer field (an uneditable text field)
1 button
When a number is placed into either input a calculation is done when the calculate button is pressed e.g. if i put in 2 in input 1 and click the button = input1 * 5 and the answer is displayed in the answer field
when 2 is put into input 2 = (input 2 + 10) * 5
when 2 is put into input 3 = input 3 + 5%
instead of having 3 input fields i would like 1 drop down list and one input
so you choose from the drop down which you want and only have 1 input field.
i don't know how to do dropdowns etc and any help would be appreciated
edit
anyone know how to on load hide the 3 inputs and then show the relivant input once it is selected from the combo box?
The drop down is called combo box in most UIs. The Java swing object is JComboBox
Here's the doc:
http://java.sun.com/javase/6/docs/api/javax/swing/JComboBox.html
And a tutorial:
http://java.sun.com/docs/books/tutorial/uiswing/components/combobox.html
I gave this a try (hope that's what you want).
With all that links and tutorials already provided, you should have been able to do that (IMO).
That's what it looks like:
Screenshot http://img97.imageshack.us/img97/9557/socombobox.png
It does not do proper exception handling, does not round the results and is not really object oriented (just uses hardcoded indexes, be careful when changing).
Add the components (called txtInput, cmbChoose, btnDo and txtResult in my case.
Edit the model property of your JComboBox, using Combo Box Model Editor and set it to
x5
plus10
plus5perc
This will generate the following source:
cmbChoose.setModel(new javax.swing.DefaultComboBoxModel(
new String[] { "x5", "plus10", "plus5perc" }));
Put the following into your JButtons ActionPerformed method.
try {
float input = Float.valueOf(txtInput.getText());
float output = 0;
switch (cmbChoose.getSelectedIndex()) {
case 0:
output = input * 5; break;
case 1:
output = input + 10; break;
case 2:
output = input * 1.05f;
}
txtResult.setText(String.valueOf(output));
} catch (Exception e) {
txtResult.setText("[Error]");
}
Sorry about the confusion.
please ignore the other post.
answer from user: italy
two approaches:
(1) Use setVisible - When you create the fields invoke setVisible(false) on each. When a selection is made in the combo box invoke setVisible(true) on the relevant input field and setVisible(false) on the others.
(2) Use one input field - when a selection is made on the combo-box change its name