eclipse 如何将 Java 文本字段传递给数组列表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/882566/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-19 13:43:28  来源:igfitidea点击:

How to pass Java textfield to an array list?

javaeclipseswing

提问by PaLoS

Guys, kindly help me how to pass the values of my inputs in my JTextField(ID,LastName,FirstName,Course,Year) into my ArrayList without replacing the existing elements. At the same i'll be using my ArrayList stored values to append in my JTextArea(summary)

伙计们,请帮助我如何将我在 JTextField(ID,LastName,FirstName,Course,Year) 中输入的值传递到我的 ArrayList 而不替换现有元素。同时,我将使用我的 ArrayList 存储值附加到我的 JTextArea(summary) 中

////// PALOS TEXTFIELD

List<Form> myList = new ArrayList<Form>();


        id = new JTextField(20);


        id.addKeyListener(new KeyAdapter()
        {
            public void keyTyped(KeyEvent ke){
                char char1 = ke.getKeyChar();
                if((!(Character.isDigit(char1))) && (char1 != '\b') ){ 
                        ke.consume(); 
                    }
                } 
            }); 
            id.addActionListener(handler);
            fname = new JTextField(20);
            fname.setFont(new Font("TimesRoman", Font.PLAIN,14));
            fname.setHorizontalAlignment(JTextField.CENTER);
            fname.setBorder(BorderFactory.createEtchedBorder(3, Color.green, Color.white));

            fname.addKeyListener(new KeyAdapter()
            {
                public void keyTyped(KeyEvent ke){
                    char char1 = ke.getKeyChar();
                    if((!(Character.isLetter(char1))) && 
                            (char1 != '\b') ) 
                            { 
                            ke.consume(); 
                            } 
                            } 
                            public void keyReleased(KeyEvent e){} 
                            public void keyPressed(KeyEvent e){} 
                            }); 
            fname.addActionListener(handler);

    lname = new JTextField(20);

    lname.addKeyListener(new KeyAdapter()
        {
            public void keyTyped(KeyEvent ke){
                char char1 = ke.getKeyChar();
                if((!(Character.isLetter(char1))) && 
                    (char1 != '\b') ) 
                    { 
                        ke.consume(); 
                    } 
                } 
                    public void keyReleased(KeyEvent e){} 
                    public void keyPressed(KeyEvent e){} 
                            }); 
    lname.addActionListener(handler);

    year = new JTextField(20);

    year.addKeyListener(new KeyAdapter()
        {
        public void keyTyped(KeyEvent ke){
            char char1 = ke.getKeyChar();
                if((!(Character.isDigit(char1))) && 
                    (char1 != '\b') ) 
                    { 
                        ke.consume(); 
                    } 
                } 
                public void keyReleased(KeyEvent e){} 
                public void keyPressed(KeyEvent e){} 
                    }); 
    year.addActionListener(handler);

    course = new JTextField(20);

        course.addKeyListener(new KeyAdapter()
        {
            public void keyTyped(KeyEvent ke){
            char char1 = ke.getKeyChar();
                if((!(Character.isLetter(char1))) && 
                    (char1 != '\b') ) 
                    { 
                        ke.consume(); 
                    } 
                } 
                    public void keyReleased(KeyEvent e){} 
                    public void keyPressed(KeyEvent e){} 
                }); 
        course.addActionListener(handler); 

////PALOS BUTTONS

    addB = new JButton(namesB[1]);
        addB.setHorizontalAlignment(JTextField.CENTER);
        addB.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            id.selectAll();
            fname.selectAll();
             lname.selectAll();
             course.selectAll();
             year.selectAll();                    
             String textID = id.getSelectedText();
             String textFName = fname.getSelectedText();
             String textLName = lname.getSelectedText();
             String textCourse = course.getSelectedText();
             String textYear = year.getSelectedText();


                     summary.setCaretPosition(summary.getDocument().getLength());

                 } 
             });

/////pALOS TEXTAREA

    summary = new JTextArea(11,31);
            summary.setBorder(BorderFactory.createEmptyBorder(0, 3, 0, 5));
            summary.setText("ID" + newtab + "FirstName " + newtab +  "LastName" + newtab + "Course" + newtab + "Year" + newline);
            summary.setEditable(false);

回答by willcodejavaforfood

I'll take a stab at it but I have to make some assumptions here.

我会尝试一下,但我必须在这里做一些假设。

// Obviously no public fields, but I cant be bothered to make constructor
// or get/set methods
public class Form
{
    public String id;
    public String lastName;
    public String firstName;
    public String course;
    public String year;
}

So you want to add a new instance of Form to your list of forms everytime that button is pressed:

因此,您想在每次按下该按钮时向表单列表中添加一个新的 Form 实例:

public class MyGui
{
    private List<Form> forms = new ArrayList<Form>();
    private JTextField fname;
    private JTextField id;
    private JTextField lname;
    private JTextField course;
    private JTextField year;
    // build gui ....
}

This is the action listener for your 'save/add' button

这是“保存/添加”按钮的动作侦听器

public void actionPerformed(ActionEvent e)
{
    Form form = new Form();
    form.id = id.getText();
    form.lastName = lname.getText();
    form.firstName = fname.getText();
    form.course = course.getText();
    form.year = year.getText();
    forms.add(form);
}

回答by akf

The pertinent part in your posted code is in your ActionListener, where you handle the button click. First off, You can maintain the ArrayListmodel you have requested as a List of Lists of Strings (List<List<String>>) - or of types defined in @willcodejavaforfood's Form structure. This way you will have an easy time of retaining previous rows. Each time the button is clicked, you can grab the data from the text fields as you have already coded and now simply add it to the model as a new row. Then you can iterate over the model and replace the data in the JTextArea.

您发布的代码中的相关部分在您的 中,您可以在ActionListener其中处理按钮单击。首先,您可以将ArrayList您请求的模型维护为字符串列表列表 (List<List<String>>) - 或@willcodejavaforfood 的表单结构中定义的类型。这样您就可以轻松地保留前几行。每次单击按钮时,您都可以从已编码的文本字段中获取数据,现在只需将其作为新行添加到模型中即可。然后您可以迭代模型并替换 JTextArea 中的数据。

The declaration of your model would look like this:

您的模型声明如下所示:

List<List<String>> model = new ArrayList<List<String>>();

and your updated action listener would look something like this:

你更新的动作监听器看起来像这样:

addB.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        id.selectAll();
        fname.selectAll();
        lname.selectAll();
        course.selectAll();
        year.selectAll();
        String textID = id.getSelectedText();
        String textFName = fname.getSelectedText();
        String textLName = lname.getSelectedText();
        String textCourse = course.getSelectedText();
        String textYear = year.getSelectedText();

        List<String> line = Arrays.asList(new String[]{textID,textFName,textLName,textCourse,textYear});
        model.add(line);

        StringBuilder sb = new StringBuilder();
        sb.append("ID\tFirst\tLast\tCourse\tYear\n");
        for(List<String> input : model) {
            for (String item : input) {
                sb.append(item);
                if (input.indexOf(item) == input.size()-1) {
                    sb.append("\n");
                } else {
                    sb.append("\t");
                }
            }
        }
        summary.setText(sb.toString());
    }
});

It is a little brute-force, but it gets the job done. There is more that can be done to ensure proper column alignment and a prettier way to ensure a newline at the end of a line, etc, but that, as they say, is left as an exercise for the reader.

这有点蛮力,但它完成了工作。可以做更多的事情来确保正确的列对齐和更漂亮的方式来确保行尾的换行符等,但正如他们所说,这留给读者作为练习。