I am trying to take the values from the text fields below to use with parent.addNewRoom(roomNo,roomEnSuite); but roomEnSuite is a Boolean value in the parent class. What is the correct procedure to get a Boolean from a JTextField?
public void actionPerformed( ActionEvent ae)
{
String item = ae.getActionCommand();
if ( item.equals("Confirm"))
{
String roomNo = nameJTextField.getText();
String roomEnSuiteS = idJTextField.getText();
parent.addNewRoom(roomNo,roomEnSuite);
this.dispose();
}
else if ( item.equals("Cancel"))
{
parent.resetButtons();
this.dispose();
}
}
To give a full answer from my above comments:
Handling boolean input using a JTextField would not be a good way to go about things as there are many variations the user could type yes/no/true/false, etc. mispelling?
Using a JRadioButton (for single answers) or JCheckbox (for multiple answers) would be a better way to go about handling true or false input. I would suggest a JRadioButton as you wouldn't want the user checking true and false.
http://docs.oracle.com/javase/tutorial/uiswing/components/button.html
Assuming the user entered the string true or false, you can turn it into a boolean with:
boolean value = Boolean.parseBoolean(idJTextField.getText());
A JTextField is meant to provide Strings. So unless you want the user to type true or false in the textfield (or whatever string you will parse to a boolean), there are better options available
a JCheckBox, which is typically used for toggle settings, like true-false
JRadioButtons (one for each setting, so two in this case)
And here a link to the corresponding Swing tutorial with examples on how to use these buttons
But if you really want to got with a textfield, then you should get the text from it and parse it by using for example Boolean.valueOf
As long as the value entered is always going to be true or false you can get a Boolean using;
boolean value = Boolean.parseBoolean(enSuiteJTextField.getText());
Related
I have a question about java / swing.
I have build an input form with some JTextFields and JComboBoxes.
And I have two Buttons. Save and Abort.
If you click Save, I check all fields for inputs. So if you miss one field an error appears.
Which works fine.
On Abort I want two cases. First case is, if something in the field is changed a JOptionPane appears with the question "Do you really want to close? Data loss blabla".
But if no inputs are made, it should just close without this message.
To check if something is changed I have this:
private boolean isFormularChanged() {
boolean isChanged = false;
for (Component c : WeinDatenPanel.getComponents()){
if (!isChanged && c instanceof JTextField) {
isChanged = !((JTextField) c).getText().isEmpty();
} else if (!isChanged && c instanceof JComboBox) {
isChanged = isComboBoxChanged;
}
}
return isChanged;
}
The problem is, that my first JTextField has a MaskFormatter and Placeholders. So the .getText().isEmpty() doesnt work for this field. And isChanged is always true because of this.
Can I somehow iterate trough all the fields without my MaskFormatter field?
An ugly solution would be to do this by hand and check all my fields by hand execpt my first one. But maybe theres another, cleaner solution?
I am building a calculator (gas law calculator) which has four text fields, and I need three fields to be filled by numbers to calculate the fourth value. The equation is v1/p1 = v2/p2. But the problem is I don't know which three values the user will fill. So I need to find an algorithm to check each text field and determine which is empty. I am using swing classes. Jut give me direction.
Thank you!
DocumentListener
to try to avoiding KeyListener
possible way could be FocusListener also, notice Focus is asynchronous
Well, what do you expect the value of the "empty" field to be?
Of course it will be the empty string, "".
So just test for which fields contents equal the empty string (or have a length of 0).
How about this?
private boolean validateField(JComponent component)
{
if (component.getText().trim().length() == 0){
return false;
}
else{
return true;
}
}
If you want to check if JTextField is empty you just do it as follows:
Example(sudo code):
-> JTextField field = new JTextField("v1:");
-> if(field.getText().isEmpty == true){...}
else{...}
I have a series of four yes/no choices in four separate dialog boxes, the cumulative results of which will lead to one of twelve separate links (e.g., Yes/Yes/Yes/No -> link A, Yes/No/No/Yes -> link B, etc). The branching logic uses boolean values.
Here's what I have so far...just the first dialog box and printing the results for validation.
public class OutageGuideSelector{
public static void main(String[] args){
boolean contactServerUp;
boolean vistaUp;
boolean stormOutage;
boolean vistaCSUp;
//
int contactServerEntry = JOptionPane.showConfirmDialog(null,
"Is the contact server up", "Please select",
JOptionPane.YES_NO_OPTION);
System.out.println("result from entry " + contactServerEntry);
if(contactServerEntry==1)
contactServerUp = true;
else
if(contactServerEntry==0)
contactServerUp = false;
/* System.out.println(contactServerUp); */
}}
Right now, the results of clicking YES reults in a 0 being returned, NO results in a 1. Is this normal, seems counterintuitive, and there's nothing at docs.oracle.java that shows a clear example of the output values except this which seems to suggest that the public static final int YES_NO_OPTION default in 0.
Additionally, the line System.out.println(contactServerUp); comes back with an error that the field contactServerUp might not have been initialized when I un-comment it, so I can't see if my convert-int-to-boolean is working.
First: It appears that JOptionPane method does not include any boolean returns...except getWantsInput() which returns the value of the wantsInput property...so I assume I'm already being the most efficient I can with this. I'd like to know if there's an easier way.
Second, what am I missing that prevents my console output statement from recognizing the contactServerUp? Where's my misplaced semicolon?
According to the javadoc, when one of the showXxxDialog methods returns an integer, the possible values are:
YES_OPTION
NO_OPTION
CANCEL_OPTION
OK_OPTION
CLOSED_OPTION
You should test against those constants:
contactServerUp = (contactServerEntry == JOptionPane.YES_OPTION);
The value returned by the the JOptionPane dialogs are values defined as constant fields in the class.
Although, indeed, one could assume that 0 means false and 1 means true, the values are more ids for the different buttons a dialog can have.
To know if the user pressed yes or no, you can compare the return value to the constant fields described here. For example, in your case :
contactServerUp = (contactServerEntry == JOptionPane.YES_OPTION);
Since a dialog a JOptionPane can have more than two possible 'answers' a boolean would be a poor representation. You are forgetting about the YES, NO and CANCEL option, or what about just a OK answer.
If it would have been written today, I suspect a Enum would have been used instead of an int.
As for the second question, the compiler does not allow access to uninitialized variables.
When you do the following, there is a chance that the variable might not be initialized:
if(contactServerEntry==1)
contactServerUp = true;
else
if(contactServerEntry==0)
contactServerUp = false;
What if, for example, contactServerEntry == JOptionPane.CLOSED_OPTION? In that case, your boolean value is never initialized.
You need to add an else clause at the end of your if-else chain, or initialize contactServerUp value to a default value in the beginning.
Does anyone know how to go about creating field that would perform telephone number format masking, like here (___) ___-____:
http://www.smartclient.com/smartgwt/showcase/#form_masking
A better approach would be to let the user type whatever they want: "789-555-1234" or "(789) 555-1234" or "7895551234" and then when the field loses focus decide if what they typed can be a phone number. If so you can reformat it as "(789) 555-1234". There are several related questions about how to do that sort of thing with regular expressions; just be sure your regex accepts the format you're changing the user's input to, otherwise it will be really annoying to edit.
As an example, look what happens when you type ".5" into the left margin field in Microsoft's standard page setup dialog: when you tab out it changes it to "0.5".
UPDATE: Here's sample code in GWT to illustrate. For the sake of this example, assume there's an element called "phoneContainer" to put the text box in. GWT doesn't give you the full java.util.regex package, but it gives enough to do this:
private void reformatPhone(TextBox phoneField) {
String text = phoneField.getText();
text = text.replaceAll("\\D+", "");
if (text.length() == 10) {
phoneField.setText("(" + text.substring(0, 3) + ") " + text.substring(3, 6) + "-" + text.substring(6, 10));
}
}
public void onModuleLoad() {
final TextBox phoneField = new TextBox();
RootPanel.get("phoneContainer").add(phoneField);
phoneField.addBlurHandler(new BlurHandler(){
public void onBlur(BlurEvent event) {
reformatPhone(phoneField);
}
});
}
It looks like you'd want to create your own widget that extends the GWT input box and has a default value set to the mask you want. Then you handle the onKeypress event and update the field as needed (making sure to set the cursor position to the correct location).
I'm trying to learn something about GUI, using NetBeans6.8, starting with the GUI section in The java tutorial.
There is a simple exercise for a Celsius-Fahrenheit converter. I want that to have two TextFields, one for Celsius and one for Fahrenheit temperature; if the user types in the celsius text field he got the result "printed" in the fahrenheit text filed. and vice versa.
So, i put on both the textfields one KeyTyped event, here's the code:
private void celsiusTextKeyTyped(java.awt.event.KeyEvent evt) {
int cels = Integer.parseInt(celsiusText.getText());
int fahr = (int)(cels * 1.8 + 32);
fahrText.setText(fahr + "");
}
private void fahrTextKeyTyped(java.awt.event.KeyEvent evt) {
int fahr = Integer.parseInt(fahrText.getText());
int cels = (int)(fahr / 1.8 - 32);
celsiusText.setText(cels + "");
}
It doesn't work. If i type something in a textfield i got this exception: java.lang.NumberFormatException: For input string: ""
The code that attach the listeners:
celsiusText.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
celsiusTextKeyTyped(evt);
}
});
fahrText.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
fahrTextKeyTyped(evt);
}
});
[However, i can't modify it, it's autogenerated.]
Method .getText() returns a string not a number, if that string contains non-numeric characters (i.e. a letter, a space, nothing at all) then parseInt will throw a NumberFormatException. Since your using KeyEvent, as soon as you press say "7", the event is fired before 7 is entered into the text box. Thus the text box still only contains "", which is where the error comes from. You may wish to also listen to the keyUp event instead.
You need to enclose your code in a try catch block.
private void fahrTextKeyTyped(java.awt.event.KeyEvent evt)
{
try
{
int fahr = Integer.parseInt(fahrText.getText());
int cels = (int)(fahr / 1.8 - 32);
celsiusText.setText(cels + "");
}
catch(NumberFormatException ex)
{
//Error handling code here, i.e. informative message to the user
}
}
An alternative is you could filter out non-numbers on keydown event, see example here - http://www.javacoffeebreak.com/java107/java107.html (Creating a custom component - NumberTextField)
I suspect that what's happened is that you added these handlers with something like celsiusText.addKeyListener, yes?
The thing is, that'll give you not just the KEY_TYPED events you wanted, but also KEY_DOWN and KEY_UP. The KEY_DOWN event will happen before the text is really entered into the field, so your code firing on that will see the field as blank still. Trying to convert the empty string to a number gives you a format exception.
The easiest way to fix this is the try/catch construct other people have been posting.
You probably set action to keyDown, this mean that even occur before the key value is "added" to textbox, while You retrieve the value from it is still empty "".
There is a simple exercise for a
Celsius-Fahrenheit converter
That is a really old example. The better approach is to use a DocumentListener, not a KeyListener.