(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
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 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.
I'm a new programmer doing a date of birth selector for part of my project. I have got everything set up apart from a few things and I am unsure of how to do these things.
ArrayList<String> years_tmp = new ArrayList<String>();
years_tmp.add("Year");
for(int years = Calendar.getInstance().get(Calendar.YEAR) ; years>=Calendar.getInstance().get(Calendar.YEAR)-90;years--)
{
years_tmp.add(years+"");
}
Y = new JComboBox(years_tmp.toArray());
Above is my part of my code for a JComboBox which lists the previous 90 years and has the word "Years" as the first object.
For my code above how would I list the years like it currently does, but to only display years which divide by four exactly (leap years)?
Also how do I make it so once the JComboBox list has been opened the selection years can not be selected so when the value is saved in my save file it does not allow the save of the word "Years"?
To get a value which can be devided be 4 without a rest you can use the modulo operator '%':
if(year % 4 == 0) {
...
}
To disallow the Selection of "year" itself, you have several ways. One could be to append an ItemListener to your ComboBox and check whether the user selected the "year" value. If the user selected this value you can print an error message or just select another value - maybe the next possible one. You also can do more fancy stuff like disabling the save Button if the user selected an invalid value..
I think this should help you to get to the right direction.
I want to verify the user input (number) in a textfield that if it's bigger than 9 or not. Note that the number from 1 to 9.
if it's bigger than 9 I want to show a jOptionPane
some code i have traied:
else
if(jTextField1.contains()){ // want to compare it if it's bigger than 9 or not
jOptionPane1.showMessageDialog(this,"Please enter the number of the tab"); // wich means from 1 to 9
}
So how to do that with java?
Thanks in advance :)
You can directly do it with help of js using jQuery just give id to our text field and add a script tag with the following code :
num = $("#yourId").val();
if(num>9){
alert("your message");
}
or any thing else you want to achieve
I'm just learning JAVA and having a bit of trouble with this particular part of my code. I searched several sites and have tried many different methods but can't seem to figure out how to implement one that works for the different possibilities.
int playerChoice = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter number for corresponding selection:\n"
+ " (1) - ROCK\n (2) - PAPER\n (3) - SCISSORS\n")) - 1;
I imagine I need to have some type of validation even for when the user has no input as well as an input that is not 1, 2 or 3. Anyone have suggestions on how I can accomplish this?
I tried a while loop, an if statement to check for null before converting the input to an integer, as well as a few different types of if else if methods.
Thanks in advance!
You need to do something like this to handle bad input:
boolean inputAccepted = false;
while(!inputAccepted) {
try {
int playerChoice = Integer.parseInt(JOption....
// do some other validation checks
if (playerChoice < 1 || playerChoice > 3) {
// tell user still a bad number
} else {
// hooray - a good value
inputAccepted = true;
}
} catch(NumberFormatException e) {
// input is bad. Good idea to popup
// a dialog here (or some other communication)
// saying what you expect the
// user to enter.
}
... do stuff with good input value
}
Read the section from the Swing tutorial on How to Make Dialogs, which actually shows you how to use JOptionPane easily so you don't need to validate the input.
There are different approaches your could use. You could use a combo box to display the choices or maybe multiple buttons to select a choice.
The tutorial also shows you how to "Stopping Automatic Dialog Closing" so you can validate the users input.