获取JTextField用户输入将返回初始空值

时间:2014-11-27 14:07:55

标签: java string swing jtextfield

在JTextFields中键入新文本时,getText会在按下“创建”按钮时继续返回JTextField的初始空值。应该添加哪些方法来将JTextField值更新为新用户输入?

public class NewQuizWindow {

    private JPanel panel;
    private JTextField[] textfields = new JTextField[4];
    private String[] inputs = new String[textfields.length];
    private JButton create;

    public NewQuizWindow() {

        panel = new JPanel();
        panel.setLayout(null);
        initialise();
    }

    public JPanel initialise(){

        //print initial labels, buttons
        JLabel l1 = new JLabel("Please fill in the required fields below.");        
        Dimension size = l1.getPreferredSize();
        l1.setBounds(225 - size.width/2, 50, size.width, size.height );
        panel.add(l1);

        JLabel title = new JLabel("Title");     
        size = title.getPreferredSize();
        title.setBounds(10, 100, size.width, size.height);
        panel.add(title);

        JLabel description = new JLabel("Description");
        size = description.getPreferredSize();
        description.setBounds(10, 130, size.width, size.height);
        panel.add(description);

        JLabel location = new JLabel("Location");
        size = location.getPreferredSize();
        location.setBounds(10, 160, size.width, size.height);
        panel.add(location);

        JLabel date_time = new JLabel("Date");
        size = date_time.getPreferredSize();
        date_time.setBounds(10, 190, size.width, size.height);
        panel.add(date_time);

        JLabel l = new JLabel("(yyyy-mm-dd)");
        l.setForeground(Color.GRAY);
        size = l.getPreferredSize();
        l.setBounds(10, 200, size.width, size.height);
        panel.add(l);

        create = new JButton("Create");
        size = create.getPreferredSize();
        create.setBounds(225- size.width/2, 230, size.width, size.height);
        panel.add(create);

        //initialise textfields
        for(int i = 0; i< textfields.length; i++){
            textfields[i] = new JTextField();
            textfields[i].setBounds(100, 95+30*i, 300, 25);
            textfields[i].setEditable(true);
            panel.add(textfields[i]);
        }

        //create actionlistener, reading textfields
        create.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {

                for(int i = 0; i< textfields.length; i++){

                    inputs[i] = textfields[i].getText();
                    System.out.println("-" +textfields[i].getText()+ "-");

                }


            }
        });

        return panel;

    }


}

0 个答案:

没有答案