[英]Get boolean from a JTextField
I am trying to take the values from the text fields below to use with parent.addNewRoom(roomNo,roomEnSuite);
我正在尝试从下面的文本字段中获取值以与
parent.addNewRoom(roomNo,roomEnSuite);
but roomEnSuite is a Boolean value in the parent class. 但是roomEnSuite是父类中的布尔值。 What is the correct procedure to get a Boolean from a JTextField?
从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? 使用
JTextField
处理boolean
输入不是解决问题的好方法,因为用户可以输入yes
/ no
/ true
/ false
等多种变体,例如拼写错误?
Using a JRadioButton
(for single answers) or JCheckbox
(for multiple answers) would be a better way to go about handling true
or false
input. 使用
JRadioButton
(用于单个答案)或JCheckbox
(用于多个答案)将是处理true
或false
输入的更好方法。 I would suggest a JRadioButton
as you wouldn't want the user checking true
and false
. 我建议使用
JRadioButton
因为您不希望用户检查true
和false
。
http://docs.oracle.com/javase/tutorial/uiswing/components/button.html http://docs.oracle.com/javase/tutorial/uiswing/components/button.html
假设用户输入字符串true
或false
,则可以使用以下命令将其转换为boolean
:
boolean value = Boolean.parseBoolean(idJTextField.getText());
A JTextField
is meant to provide String
s. JTextField
旨在提供String
。 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 因此,除非您希望用户在文本字段(或将解析为布尔值的任何字符串)中输入
true
或false
,否则会有更好的选择
JCheckBox
, which is typically used for toggle settings, like true-false JCheckBox
,通常用于切换设置,例如true-false JRadioButton
s (one for each setting, so two in this case) JRadioButton
(每个设置一个,因此在这种情况下两个) And here a link to the corresponding Swing tutorial with examples on how to use these buttons 这里是指向相应的Swing教程的链接,其中包含有关如何使用这些按钮的示例
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
但是,如果您真的想使用文本字段,则应该从中获取文本并使用例如
Boolean.valueOf
进行解析。
只要输入的值始终为true或false,就可以使用布尔值;
boolean value = Boolean.parseBoolean(enSuiteJTextField.getText());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.