JTextField ActionListener in GridBagLayout
Asked Answered
Q

2

0

I am having troubles adding an actionlistener to my JTextField. I need to get the text entered from the user into a string so i can work with it.

Can anyone tell me what im doing wrong or how i should do it.

Here is the code:

public void actionPerformed(ActionEvent e)
        {
            //Execute when button is pressed
            JFrame frame = new JFrame("Value Bet");
            frame.setVisible(true);
            frame.setSize(500,300);
            GridBagLayout layout = new GridBagLayout();
            frame.setLayout(layout);
            GridBagConstraints c = new GridBagConstraints();

            JLabel label;
            JTextField tf;

            if (shouldFill) {
            //natural height, maximum width
            c.fill = GridBagConstraints.HORIZONTAL;
            }
            if (shouldWeightX) {
            c.weightx = 0.5;
            }

            ...

            tf = new JTextField();
            c.fill = GridBagConstraints.HORIZONTAL;
            c.gridx = 1;
            c.gridy = 2;
            frame.add(tf, c);
            tf.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e)
                {
                    String chance1 = tf.getText();
                }
            });

...
Quick answered 31/5, 2012 at 22:24 Comment(0)
T
1

Why are you using ActionListener instead of KeyListener?

You should use KeyListener or:

tf.getDocument().addDocumentListener(documentListener);

DocumentListener

Teresetereshkova answered 31/5, 2012 at 22:29 Comment(1)
Will document listener allow me to store the user input in a variable as well? And how?Quick
M
1
public void actionPerformed(ActionEvent e)
{
    //  Look Ma, a one-liner!
    String chance1 = JOptionPane.showInputDialog(someComponent, "Value Bet");
}

option pane one-liner

Look further into the overloaded methods to tweak the look, for robustness add a null check, and consider using a spinner instead of the text field (BNI).

Mastership answered 1/6, 2012 at 7:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.