1 回答

TA貢獻1851條經驗 獲得超5個贊
有很多方法可以做你想要的,所以這里只是其中之一:
您需要為每個文本字段添加一個動作偵聽器,并讓它們設置一個公共變量(對文本字段的引用),以便您的代碼知道最后選擇哪個文本字段。然后,當您單擊按鈕時,您可以簡單地使用該變量來了解選擇了哪個文本字段并在末尾添加 1,或者執行您想做的任何其他操作,只需編輯事件即可。
示例代碼:
//Value to keep track of the last selected text field
public static JTextField lastClicked;
private static javax.swing.JButton jButton1;
private static javax.swing.JTextField jTextField1;
private static javax.swing.JTextField jTextField2;
public static void main(String args[])
{
//Create and display the form
java.awt.EventQueue.invokeLater(new Runnable()
{
public void run()
{
//Setup all the components
jButton1 = new javax.swing.JButton("Click Me");
jTextField1 = new javax.swing.JTextField("One");
jTextField2 = new javax.swing.JTextField("Two");
//Add listeners
jButton1.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
//Add a 1 to the last selected text field
lastClicked.setText(lastClicked.getText() + "1");
}
});
jTextField1.addFocusListener(new java.awt.event.FocusAdapter()
{
public void focusGained(java.awt.event.FocusEvent evt)
{
//change the selected text field to this one
lastClicked = (JTextField) evt.getSource();
}
});
jTextField2.addFocusListener(new java.awt.event.FocusAdapter()
{
public void focusGained(java.awt.event.FocusEvent evt)
{
//change the selected text field to this one
lastClicked = (JTextField) evt.getSource();
}
});
}
});
}
請注意,在此示例中,我們將事件源強制轉換為文本字段lastClicked = (JTextField) evt.getSource(),因此這僅適用于文本字段。如果要使用其他組件,則應使用整數或對象作為變量類型。
添加回答
舉報