[英]Swing get JTextField upon JButton press
顯然,我的Google-fu技能有些遲鈍,按JButton時我不知道如何獲取JTextField。
請注意,為了便於閱讀,我刪除了部分代碼。
如果看到一些未定義的變量,請假定它是該代碼的一部分。
就目前而言,代碼可以正常工作。
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
獲取所述textfield值。
我意識到我可以使用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方法中使用它。
祝您編程愉快,萬事如意!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.