'User input from a JTextField to a message box

I need to take text that a user has inputted into a text field and display it in a message box (a JOptionPane) after a button has been clicked.

Here is the code I have tried:

private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {
    JOptionPane.showMessageDialog(null.getTextField1);


Solution 1:[1]

you should use the function getText() from the JTextField, the code could be:

private JButton button;
private JTextField textField;

private void initComponents() {

    textField = new JTextField ("Type some text here");
    button = new JButton("Accept");
    button.addActionListener(new ActionListener() { 
        public void actionPerformed(ActionEvent e) {
            String text = textField.getText();
            JOptionPane.showMessageDialog(null, text);
        }
    });
   panel.add(textField);
   panel.add(button);
   frame.getContentPane().add(panel);
}

So, the logic of the program is: Once the button is pressed, you create a String variable which contains the value of the textfield using the function getText() and then create a Message Dialog with that variable as argument. I hope it works!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1