我在運行時創建了JTextFields數組。這是基於用戶輸入的。因此,爲每個文本字段分配單獨的操作偵聽器。是否可以動態添加擺動控制動作偵聽器?
我如何爲TextField提供actionlisterner?
代碼:
public class BucketInfoDynamic extends javax.swing.JFrame {
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
int value;
JPanel[] p2 ;
JTextField[] txtFrom;
JTextField[] txtTo;
JLabel[] lblBucket;
JLabel lblEnd;
public BucketInfoDynamic() {
for(;;)
{
try{
String number = JOptionPane.showInputDialog("How many Bucket do you want?");
value = Integer.parseInt(number);
if(value <= 5 && value > 1)
break;
else
JOptionPane.showMessageDialog(this, "Enter bucket value should greater than 1 and less than 5.\n");
}
catch(NumberFormatException ex)
{
JOptionPane.showMessageDialog(this, "This is Not a valid number format..\n");
}
}
initComponents();
jPanel1.setLayout(new GridLayout(value,1,20,10));
p2 = new JPanel[value];
txtFrom = new JTextField[value];
txtTo = new JTextField[value -1];
lblBucket = new JLabel[value];
lblEnd = new JLabel("And Above");
this.designProcess();
}
private void designProcess() {
jPanel1.setSize(value * 50 ,jPanel1.getWidth());
for(int i = 0; i < value; i++)
{
lblBucket[i] = new JLabel("Bucket "+i);
p2[i] = new JPanel();
p2[i].setLayout(new GridLayout(1,3,20,10));
txtFrom[i] = new JTextField();
if(i == 0)
txtFrom[i].setText("0");
txtFrom[i].setEditable(false);
p2[i].add(lblBucket[i]);
p2[i].add(txtFrom[i]);
if(i < value-1)
{
txtTo[i] = new JTextField();
txtTo[i].setFocusTraversalKeysEnabled(false);
txtTo[i].addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
toKeyReleased(evt);
}
});
p2[i].add(txtTo[i]);
}
else
p2[i].add(this.lblEnd);
jPanel1.add(p2[i]);
}
}
private void toKeyReleased(KeyEvent evt) {
// this.checkFormat(evt);
Component com = evt.getComponent();
System.out.println(com.getName());
if(KeyEvent.VK_TAB == evt.getKeyCode())
this.checkRange();
}
}
只需將監聽器添加到'JTextField' ......你已經有了它創建的代碼場。它是[add](http://docs.oracle.com/javase/7/docs/api/javax/swing/JTextField.html#addActionListener(java.awt.event.ActionListener))的一個' ActionListener'也是如此。 – Robin 2012-07-21 07:50:00
我有TextField的數組。所以我需要單獨的actionlistener爲每個字段 – Dhinakar 2012-07-21 07:54:14
*「我已經創建了文本框」*什麼是「文本框」? – 2012-07-21 16:26:01