我在运行时创建了 JTextField 数组。这是基于用户输入的。因此,为每个文本字段分配单独的动作侦听器。
我如何为 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();
}
}