[英]Have Focus on one JTextField and perform an action related to it
My Application has two JTextField's and one JButton. 我的应用程序有两个JTextField和一个JButton。
I want a code snippet where in 我想要一个代码片段
EDIT : What I am trying to do (numInput , denInput are both JTextFields) 编辑: 我想做的事情 (numInput,denInput都是JTextFields)
public void actionPerformed(ActionEvent e) {
String s = e.getActionCommand();
if (numInput.isFocusOwner()) {
if (s.equals("1")) {
if (z == 0) {
numInput.setText(numInput.getText() + "1");
} else {
numInput.setText("");
numInput.setText(numInput.getText() + "1");
z = 0;
}
}
else if (denInput.isFocusOwner()) {
if (s.equals("1")) {
if (z == 0) {
denInput.setText(numInput.getText() + "1");
} else {
denInput.setText("");
denInput.setText(numInput.getText() + "1");
z = 0;
}
}
}
This never works for me. 这对我永远不起作用。
Create an Action
that extends TextAction
and add this Action
to your button. 创建一个扩展
TextAction
的Action
并将该Action
添加到您的按钮。
TextAction
has a getFocusedComponent()
method that will return the last text component that had focus. TextAction
具有getFocusedComponent()
方法,该方法将返回具有焦点的最后一个文本组件。
The basic code for the Action would be: 该操作的基本代码为:
TextAction action = new TextAction("")
{
@Override
public void actionPerformed(ActionEvent e)
{
JTextComponent textField = getFocusedComponent();
System.out.println( textField.getText() );
}
};
This will only work if you only have two text field on the form. 仅当表单上只有两个文本字段时,这才起作用。 If you have more than two then you would need to add extra code to verify that focus was on either of the two text fields before the button was clicked.
如果您有两个以上,则在单击按钮之前,需要添加额外的代码来验证焦点是否在两个文本字段中的任何一个上。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.