JTextField ActionListener in GridBagLayout

2019-09-14 23:16发布

问题:

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();
                }
            });

...

回答1:

Why are you using ActionListener instead of KeyListener?

You should use KeyListener or:

tf.getDocument().addDocumentListener(documentListener);

DocumentListener



回答2:

public void actionPerformed(ActionEvent e)
{
    //  Look Ma, a one-liner!
    String chance1 = JOptionPane.showInputDialog(someComponent, "Value Bet");
}

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).