I dont know how to make dropdown in java
(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 input开发者_运维技巧s 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 JButton
s 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
精彩评论