我有一个带有 Actionlistener 的 JTextField。现在我希望它在我按 Enter 时执行某些操作。我正在使用共享的 ActionListener,因此尝试在 JTextField 上执行 getSource 但它不起作用!希望大家能够帮忙。
JTextField txtProductAantal = new JTextField(String.valueOf(WinkelApplication.getBasket().getProductAmount(productdelete)));
txtProductAantal.setBounds(340, verticalPosition + i * productOffset, 40, 20);
txtProductAantal.addActionListener(this);
add(txtProductAantal);
public void actionPerformed(ActionEvent event) {
if (event.getSource() == btnEmptyBasket) {
WinkelApplication.getBasket().empty();
WinkelApplication.getInstance().showPanel(new view.CategoryList());
}
if(event.getSource() == txtProductAantal){
String productgetal = txtProductAantal.getText();
txtProductAantal.setText(productgetal);
WinkelApplication.getInstance().showPanel(new view.Payment());
}
}
最佳答案
- 必须创建一个临时
对象
用于比较
例如
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if (source == btnEmptyBasket) {
//...........
} else if (source == txtProductAantal) {
//...........
} else {
}
}
- 或者只有
JTextFields
(避免在if - else
语句内使用instanceof
),您可以将对象转换为JTextField
> 直接
JTextField source = (JTextField) event.getSource();
编辑,
下一个建议的 17 个问题。
请再次阅读@Andrew Thompson 的建议
1) 为了更快地获得更好的帮助,请发布 SSCCE。
2) txtProductAantal.setBounds(..)
使用布局可以避免接下来的 17 个问题。
我的代码按照我的预期工作
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class JTextFieldAndActionListener implements ActionListener {
private JFrame frm = new JFrame("JTextFieldAndActionListener");
private JTextField one = new JTextField(10);
private JTextField two = new JTextField();
private JTextField three = new JTextField();
public JTextFieldAndActionListener() {
one.addActionListener(this);
two.addActionListener(this);
three.addActionListener(this);
frm.setLayout(new GridLayout());
frm.add(one);
frm.add(two);
frm.add(three);
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frm.setLocation(400, 300);
frm.pack();
frm.setVisible(true);
}
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if (source == one) {
System.out.println("firing from JTextField one");
} else if (source == two) {
System.out.println("firing from JTextField two");
} else if (source == three) {
System.out.println("firing from JTextField three");
} else {
System.out.println("something went wrong");
}
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JTextFieldAndActionListener ie = new JTextFieldAndActionListener();
}
});
}
}
按 ENTER 键打印_输出
run:
firing from JTextField one
firing from JTextField two
firing from JTextField three
BUILD SUCCESSFUL (total time: 15 seconds)
关于java - 输入键 JTextField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14197098/