如何使动作侦听器求和上述循环?我究竟做错了什么?也许我应该将总和放在第一个循环中,而不是另一个放到动作侦听器中。还是我的动作监听器有问题?请有人指出我的错误。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Arrays;
public class Bton extends javax.swing.JFrame {
JPanel pan = (JPanel) this.getContentPane();
JLabel []lab = new JLabel[4];
JTextField []text = new JTextField[4];
Border border = BorderFactory.createLineBorder(Color.grey,1);
JButton b = new JButton("Calculate");
public Bton() {
initComponents();
pan.setLayout(null);
for(int i=0; i<lab.length ;i++){
lab[i] = new JLabel();
text[i] = new JTextField();
lab[i].setBounds(new Rectangle(15,(i+1)*40, 60, 25));
lab[i].setText("Box #" + (i+1));
lab[i].setBorder(border);
text[i].setBounds(new Rectangle(100,(i+1)*40, 60, 25));
pan.add(lab[i],null);
pan.add(text[i],null);
setSize(200,420);
setTitle("Sum tab.");
}
JLabel labe = new JLabel();
labe.setBounds(new Rectangle(15, 330, 60, 25));
labe.setText("Total Sum");
labe.setBorder(border);
JTextField txt = new JTextField(6);
txt.setBounds(new Rectangle(100, 330, 60, 25));
b.setBounds(70, 290, 89, 23);
add(b);
b.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int sum = 0;
for(int i=0; i<lab.length ;i++){
sum =+ Integer.parseInt(text[i].getText());
}
txt.setText(String.valueOf(sum));
}
});
pan.add(labe);
pan.add(txt);
}