GridBagLayout中的JTextField ActionListener [英] JTextField ActionListener in GridBagLayout

查看:111
本文介绍了GridBagLayout中的JTextField ActionListener的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在将动作侦听器添加到JTextField时遇到麻烦.我需要将用户输入的文本输入字符串,以便我可以使用它.

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.

这是代码:

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

...

推荐答案

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

进一步查看重载的方法以调整外观,为增强鲁棒性,请添加null检查,并考虑使用微调器而不是文本字段(BNI).

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

这篇关于GridBagLayout中的JTextField ActionListener的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆