简体   繁体   English

如何在java.swing JTextField中存储字符串或整数?

[英]How to store string or integer in java.swing JTextField?

Hello I am working on this project to store student names and record their grades. 您好,我正在这个项目中存储学生姓名并记录他们的成绩。 I have the entire program mapped out and all I need to do now is record the integers and strings from the user input and call it from different classes. 我已经规划了整个程序,现在要做的就是记录用户输入中的整数和字符串,并从不同的类调用它。 I am having trouble with this. 我对此有麻烦。 Do I use an array? 我是否使用数组? How do I call from another class? 我怎么从另一个班级打来电话? Thank you. 谢谢。

    package gradebook;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.util.Scanner;
import java.awt.event.ActionEvent;
import javax.swing.JTextArea;

public class Student extends JFrame {
    private JFrame studentFrame;
    private JPanel contentPane;
    private JTextField studentNameTextField;
    protected Component frame;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Student frame = new Student();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public Student() {

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JLabel gradebookLabel = new JLabel("Gradebook");
        gradebookLabel.setBounds(189, 6, 68, 16);
        contentPane.add(gradebookLabel);

        JLabel lblPleaseEnterThe = new JLabel("Please enter the student name");
        lblPleaseEnterThe.setBounds(130, 105, 194, 16);
        contentPane.add(lblPleaseEnterThe);

        studentNameTextField = new JTextField("Enter here");
        String stdname = studentNameTextField.getText();
        studentNameTextField.setBounds(130, 133, 194, 26);
        contentPane.add(studentNameTextField);
        studentNameTextField.setColumns(10);

        JButton continueButton = new JButton("Continue");
        continueButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent a) {
                if(continueButton.isEnabled()){
                Student.this.dispose();
                    Student studentScreen = new Student();
                    studentScreen.dispose();

                    AddGrades addGradesScreen = new AddGrades();
                    addGradesScreen.setVisible(true);


                }
            }
        });
        continueButton.setBounds(327, 243, 117, 29);
        contentPane.add(continueButton);

        JButton cancelButton = new JButton("Cancel");
        cancelButton.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent a) {


                if(cancelButton.isEnabled()){




                    MainScreen mainScreenScreen = new MainScreen();
                    mainScreenScreen.setVisible(true);
                    contentPane.setVisible(false);
                    contentPane.disable();


                }
            }
        });


        cancelButton.setBounds(207, 243, 117, 29);
        contentPane.add(cancelButton);
    }

    private void initizalize() {
        // TODO Auto-generated method stub

    }
}

Is it something along the lines of this? 这是否符合要求?

studentNameTextField = new JTextField("Enter here");
        String stdname = studentNameTextField.getText();

I know this would be storing it but how do I call that in a different class so I can make it appear on a different Frame? 我知道这将存储它,但是如何在不同的类中调用它,以便使它出现在不同的Frame上?

Update: Okay so I've done this 更新:好的,我已经完成了

Student frame = new Student();
        String stdname = frame.studentNameTextField.getText();
        JLabel addgradesLabel = new JLabel("Add grades for" + frame.studentNameTextField);
        addgradesLabel.setBounds(139, 34, 167, 29);
        contentPane.add(addgradesLabel);

And it's still not working. 而且仍然无法正常工作。 I believe I'm not implementing this correctly. 我相信我没有正确执行此操作。 I'm trying to title the label with what the user inputs for the name. 我正在尝试使用用户输入的名称来为标签加上标题。 So it would but "Add grades for" + stdname But it's not calling it correctly. 因此,它只能使用“为...添加成绩” + stdname,但调用方式不正确。 How can I fix this? 我怎样才能解决这个问题?

Here is my code from the AddStudentName class 这是我的AddStudentName类的代码

studentNameTextField = new JTextField();
        studentNameTextField.setBounds(130, 133, 194, 26);
        contentPane.add(studentNameTextField);
        studentNameTextField.setColumns(10);

        JButton continueButton = new JButton("Continue");
        continueButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent a) {
                if(continueButton.isEnabled()){
                Student.this.dispose();
                    Student studentScreen = new Student();
                    studentScreen.dispose();


                    AddGrades addGradesScreen = new AddGrades();
                    addGradesScreen.setVisible(true);




                }
            }
        });

What should I add here to save the input that the user is inputting into the JTextField? 我应该在此处添加什么以保存用户输入到JTextField中的输入? Thanks for the help 谢谢您的帮助

Here's the full code for the classes: 这是这些类的完整代码:

package gradebook;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.util.Scanner;
import java.awt.event.ActionEvent;
import javax.swing.JTextArea;

public class Student extends JFrame {
    private JFrame studentFrame;
    private JPanel contentPane;
    public JTextField studentNameTextField;
    protected Component frame;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Student frame = new Student();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public Student() {

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JLabel gradebookLabel = new JLabel("Gradebook");
        gradebookLabel.setBounds(189, 6, 68, 16);
        contentPane.add(gradebookLabel);

        JLabel lblPleaseEnterThe = new JLabel("Please enter the student name");
        lblPleaseEnterThe.setBounds(130, 105, 194, 16);
        contentPane.add(lblPleaseEnterThe);


        JTextField studentNameTextField = new JTextField();

        studentNameTextField.setBounds(130, 133, 194, 26);
        contentPane.add(studentNameTextField);
        studentNameTextField.setColumns(10);

        JButton continueButton = new JButton("Continue");
        continueButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent a) {
                if(continueButton.isEnabled()){

                    Student studentScreen = new Student();
                    studentScreen.dispose();

                    AddGrades addGradesScreen = new AddGrades();
                    addGradesScreen.setVisible(true);



                }
            }
        });


        continueButton.setBounds(327, 243, 117, 29);
        contentPane.add(continueButton);

        JButton cancelButton = new JButton("Cancel");
        cancelButton.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent a) {


                if(cancelButton.isEnabled()){




                    MainScreen mainScreenScreen = new MainScreen();
                    mainScreenScreen.setVisible(true);
                    contentPane.setVisible(false);
                    contentPane.disable();


                }
            }
        });


        cancelButton.setBounds(207, 243, 117, 29);
        contentPane.add(cancelButton);
    }

    private void initizalize() {
        // TODO Auto-generated method stub

    }
}

and: 和:

package gradebook;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class AddGrades extends JFrame {

    private JPanel contentPane;
    private JTextField Assignment1;
    private JTextField Assignment2;
    private JTextField Assignment3;
    private JTextField Assignment4;
    private JLabel testsLabel;
    private JTextField Test1;
    private JTextField Test2;
    public JTextField Test3;
    public JTextField Test4;

    /**
     * Launch the application.
     */
    public JFrame frame;
    public JButton continueButton;
    public JButton exitButton;
    public static void main(String[] args) {
        AddGrades frame = new AddGrades();
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    AddGrades frame = new AddGrades();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public AddGrades() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JLabel gradebookLabel = new JLabel("Gradebook");
        gradebookLabel.setBounds(189, 6, 68, 16);
        contentPane.add(gradebookLabel);


        JLabel addgradesLabel = new JLabel("Add grades for" + stdname);
        addgradesLabel.setBounds(139, 34, 167, 29);
        contentPane.add(addgradesLabel);

        JLabel assignmentsLabel = new JLabel("Assignments:");
        assignmentsLabel.setBounds(19, 75, 86, 16);
        contentPane.add(assignmentsLabel);

        Assignment1 = new JTextField();
        Assignment1.setBounds(54, 91, 130, 26);
        contentPane.add(Assignment1);
        Assignment1.setColumns(10);

        Assignment2 = new JTextField();
        Assignment2.setBounds(54, 129, 130, 26);
        contentPane.add(Assignment2);
        Assignment2.setColumns(10);

        Assignment3 = new JTextField();
        Assignment3.setBounds(54, 167, 130, 26);
        contentPane.add(Assignment3);
        Assignment3.setColumns(10);

        Assignment4 = new JTextField();
        Assignment4.setBounds(54, 205, 130, 26);
        contentPane.add(Assignment4);
        Assignment4.setColumns(10);

        testsLabel = new JLabel("Tests:");
        testsLabel.setBounds(243, 75, 38, 16);
        contentPane.add(testsLabel);

        Test1 = new JTextField();
        Test1.setBounds(262, 91, 130, 26);
        contentPane.add(Test1);
        Test1.setColumns(10);

        Test2 = new JTextField();
        Test2.setBounds(262, 129, 130, 26);
        contentPane.add(Test2);
        Test2.setColumns(10);

        Test3 = new JTextField();
        Test3.setBounds(262, 167, 130, 26);
        contentPane.add(Test3);
        Test3.setColumns(10);

        Test4 = new JTextField();
        Test4.setBounds(262, 205, 130, 26);
        contentPane.add(Test4);
        Test4.setColumns(10);

        continueButton = new JButton("Continue");
        continueButton.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent a){
                if (continueButton.isEnabled()){

                    MainScreen mainScreenScreen = new MainScreen();
                    mainScreenScreen.setVisible(true);

                }


            }
        });
        continueButton.setBounds(327, 243, 117, 29);
        contentPane.add(continueButton);

        exitButton = new JButton("Exit");

        exitButton.setBounds(208, 243, 117, 29);
        contentPane.add(exitButton);
    }
}

I'm trying to take the input from the JTextField 我正在尝试从JTextField中获取输入

JTextField studentNameTextField = new JTextField();

and set it on the label 并设置在标签上

JLabel addgradesLabel = new JLabel("Add grades for" + stdname);

Where stdname would be the user input from the JTextField. 其中stdname是JTextField的用户输入。

Now I'm getting errors from 现在我收到错误消息

public static void main(String[] args) {
        AddGrades frame = new AddGrades();
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    AddGrades frame = new AddGrades();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

AddGrades frame = new AddGrades(); AddGrades框架=新的AddGrades(); gives me error Add argument to match AddGrades(String) 给我错误添加参数以匹配AddGrades(String)

The constructor AddGrades() is undefined 构造函数AddGrades()未定义

Edit: The best way to do this is to pass an argument to your newly created AddGrades class. 编辑:做到这一点的最佳方法是将参数传递给新创建的AddGrades类。 See below: 见下文:

public AddGrades(String stdname) {
    JLabel addgradesLabel = new JLabel("Add grades for " + stdname);
}

You will need to modify your code to pass a string to your AddGrades class wherever you create it: 无论您在何处创建字符串,都需要修改代码以将字符串传递给AddGrades类:

JButton continueButton = new JButton("Continue");
continueButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent a) {
        if(continueButton.isEnabled()){

            Student studentScreen = new Student();
            studentScreen.dispose();

            AddGrades addGradesScreen = new AddGrades(studentNameTextField.getText());
            addGradesScreen.setVisible(true);
        }
    }
});

That worked for me - I downloaded your code and tested it. 这对我有用-我下载了您的代码并对其进行了测试。

JSpinner or JFormattedTextField would be my first thought, but if you can't do that then you could use Integer.parseInt to parse a String to int and a NumberFormat to format the numbers to String s JSpinnerJFormattedTextField是我的第一个想法,但是如果您不能这样做,则可以使用Integer.parseIntString解析为int并使用NumberFormat将数字格式化为String

Maybe have a look at How to Use Spinners and How to Use Formatted Text Fields for starters 也许看看初学者如何使用微调框格式化文本字段

I know this would be storing it but how do I call that in a different class so I can make it appear on a different JFrame? 我知道这将存储它,但是如何在不同的类中调用它,以便使它出现在不同的JFrame上?

That's a open question with little context. 这是一个几乎没有上下文的开放性问题。 You might use some kind of "model" which represented one or more Student values; 您可以使用代表一个或多个Student价值观的某种“模型”。 you might use a Observer Pattern to allow the editor to generate events to interested parties which would tell them that something has changed; 您可以使用观察者模式来允许编辑器为感兴趣的各方生成事件,这些事件将告诉他们某些事情已经改变; you might use a Model-View-Controller ; 您可以使用Model-View-Controller ; you might use a modal dialog and when it's closed, ask the editor for the values via getters. 您可能会使用模式对话框,当对话框关闭时,通过getter向编辑器询问值。

Have a look at How to Make Dialogs for more details 看看如何制作对话框了解更多详细信息

One of things you want to keep in mind is "responsibility" and "encapsulation". 您要记住的一件事是“责任”和“封装”。 You don't want outside parties to have uncontrolled access into your editor or model, this could allow them to modify the state in an uncontrolled way leading to inconsistencies in your data or UI. 您不希望外部方不受控制地访问您的编辑器或模型,这可能使外部方以不受控制的方式修改状态,从而导致数据或UI不一致。

You need to decide who is actually responsible for modifying the state of the model. 您需要确定谁真正负责修改模型的状态。 There's no "right" answer, for example, you could have the editor either be capable of editing existing student objects or creating new ones based on how it's configured, equally, you could also have the editor be "dumb" and simply use setters to setup the editor and getters to get the values. 没有“正确”的答案,例如,您可以让编辑器能够编辑现有的学生对象或根据其配置方式创建新的对象,同样,您也可以使编辑器“笨拙”并仅使用设置器即可设置编辑器和获取器以获取值。

There are lots of options available to you, which you would use would be based on the context in which you want to use it. 您可以使用许多选项,这些选项将根据您要使用的上下文而定。 My gut feeling is start with an observer pattern and a modal dialog. 我的直觉是从观察者模式和模式对话框开始的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM