显然我的 Google-fu 技能有点乏善可陈,我不知道如何在按下 JButton 时获取 JTextField。
请注意,为了便于阅读,我删除了部分代码。
如果您看到某个 undefined variable ,则假设它是该代码的一部分。
就目前情况而言,代码运行良好。
public final class Main {
// Some removed code was here
private void prepareGUI() {
// Top right stuff
JPanel topRightPanel = new JPanel();
topRightPanel.setLayout(new FlowLayout());
JLabel topRightLabel = new JLabel("Address");
JTextField topRightTextField = new JTextField("", 15);
topRightTextField.setName("add_address");
JButton topRightButton = new JButton("Add");
topRightButton.setName("add_btn");
topRightPanel.add(topRightLabel);
topRightPanel.add(topRightTextField);
topRightPanel.add(topRightButton);
mainFrame.add(topRightPanel);
// The button in question. Very suggestive name, I know.
topRightButton.addActionListener(new GenericButtonListener());
genericButtonListener.setKernel(kernel);
// some other non relevant stuff here
mainFrame.setVisible(true);
}
}
<小时/>
public class GenericButtonListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
JButton btn = (JButton) e.getSource();
String btnName = btn.getName();
if(btnName.toLowerCase().contains("add_btn")) {
addBtn(btn);
}
}
public void addBtn(JButton button){
SshFileIO sshFileIO = kernel.getFileIO();
// Get field text here
}
}
我当前的困境是如何在 GenericButtonListener
中获取所述文本字段值。
我意识到我可以使用getText
获取文本字段值,但是我无权访问 actionPerformed
函数内的该变量。
我认为这更多的是一个范围界定问题,而不是其他问题。
我只需要一些指向正确方向的指示,无需手持。
很明显,我对 Java 还很陌生。
最佳答案
请尝试使用 GenericButtonListener 的构造函数获取 topRightTextField 的引用。存储为类的属性并在 actionPerformed 中使用它。
更改此:
topRightButton.addActionListener(new GenericButtonListener());
对此:
topRightButton.addActionListener(new GenericButtonListener(topRightTextField));
并在类 GenericButtonListener 添加字段:
private JTextField topRightTextField;// set it in the constructor
然后在您的方法 actionPerformed 中使用它。
祝你编码愉快,祝你好运!
关于java - 按下 JButton 时 Swing 获取 JTextField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53476871/