Search code examples
javaswingjtextfield

How to capture user input multiple times in a JTextField


Could you help me with this little problem? I'm trying to make a menu system which shows the options in a JEditorPane, it's something like this:

Welcome

Select an option. 1.) New register. 2.) New input. 3.) Exit.

the options are chosen by the user through a JTextField, when "1" is entered it shows another menu:

New register

1.) Option X. 2.) Option Y. 3.) Back.

and so on, the problem is that I don't know how I can capture the user's input, advance to the next menu, and re-capture the user's input all in a JTextField.

textField.addActionListener(new ActionListener () {

        public void actionPerformed(ActionEvent e) {
            String cap = "";

            cap = textField.getText();

            switch(cap) {

            case "1":
                paintEditorPane("Welcome");

                    // here is my problem, I don't know how to re-capture JTextField input
                 switch(cap){

                 case "1":
                       paintEditorPane("NewRegister");
                       break;
                    }
            break;
            }
        }
    });

Solution

  • Here's Basic. Now you have to make many cases to judge states.

    public static class MainPanel extends JPanel{
        private JTextArea textArea;
    
        public MainPanel() {
            this.setLayout(new BorderLayout());
            this.textArea = new JTextArea();// you can use constructor to set Text but I like use method "setText".
            this.textArea.addKeyListener(new keyHandler());
            this.textArea.setText("Welcome\r\nSelect an option. 1.) New register. 2.) New input. 3.) Exit.\r\n");
            this.textArea.setCaretPosition(this.textArea.getText().length());// move caret to last
            this.add(this.textArea, BorderLayout.CENTER);
        }
    
        public void addText(String text) {textArea.setText(textArea.getText() + "\r\n" + text +"\r\n");}
    
        public class keyHandler extends KeyAdapter{
            @Override
            public void keyReleased(KeyEvent e) {
                switch(e.getKeyCode()){
                case KeyEvent.VK_1 : addText("New register"); break;
                case KeyEvent.VK_2 : addText("New input"); break;
                case KeyEvent.VK_3 : addText("Exit"); break;
                }
            }
        }
    }
    

    enter image description here