0

很抱歉打扰大家。

总体问题:我正在尝试打开一个对话框让用户输入内容然后关闭它

问题:-没有调用函数(我认为)-主要问题是当我使用调试时它工作正常,所以我很难找到问题

我在使用 JButtons 时遇到问题,它可以在调试中工作,但不能正常运行。这可能是因为我使用的是无限循环。有人在线建议我使用 SwingUtilities 但这不起作用(至少我不认为。

/**
 *
 * @author Deep_Net_Backup
 */
public class butonTest extends JFrame  {
String name;
boolean hasValue;

//name things
private JLabel m_nameLabel;
private JTextField m_name;

//panel
private JPanel pane;

//button
private JButton m_submit;

//action listener for the button submit
class submitListen implements ActionListener {
    public void actionPerformed(ActionEvent e) {
        submit();
        System.out.println("Test");
    }
}

//constructor
public butonTest(){
    //normal values
    name = null;
    hasValue = false;
    //create the defauts
    m_nameLabel = new JLabel("Name:");
    m_name = new JTextField(25);
    pane = new JPanel();
    m_submit = new JButton("Submit");
    m_submit.addActionListener(new submitListen());
    //

    setTitle("Create Cat");
    setSize(300,200);
    setResizable(false);

    //add components
    pane.add(m_nameLabel);
    pane.add(m_name);

    pane.add(m_submit);

    add(pane);
    //last things
    setVisible(true);
    setDefaultCloseOperation(EXIT_ON_CLOSE);

}

//submit
private void submit()
{
    System.out.println("submit");
    name = m_name.getText();
    hasValue = true;
}

//hasValue
public boolean hasValue()
{
    return(hasValue);

}

//get the text name
public String getName()
{
    return(name);
}

public void close()
{
    setVisible(false);
    dispose();
}

public static void main(String[] args)
{

    /* Test 1
    boolean run = true;
    String ret = new String();
    butonTest lol = new butonTest();

    while(run)
    {
        if(lol.hasValue())
        {
            System.out.println("Done");
            run = false;
            ret = new String(lol.getName());
            lol.close();
        }
    }



    System.out.println(ret);*/

    //Tset 2
    /*
    SwingUtilities.invokeLater(new Runnable(){
        @Override
        public void run() {
            butonTest lol = new butonTest();
            if(lol.hasValue())
            {
                System.out.println(lol.getName());
            }
        }
    });*/

}

}

编辑:它是如何不工作的:当我运行测试时,程序将打印测试并提交,然后它应该将 hasValue 更改为 true。这将(希望)允许 if 语句运行以打印完成。这不会发生。

编辑 2:我刚刚添加了几行以进一步测试 2 个打印,这似乎解决了问题(但这很糟糕) System.out.println("hasValue " + hasValue); -> 到 hasValue() 函数 System.out.println("set to true"); -> 提交()函数

4

2 回答 2

1

您正在做的事情过于复杂而不是必要的。您可以将其作为匿名类,而不是将侦听器作为单独的类。这样你就可以获得外部类(buttonTest.this)的句柄,并调用你想要的任何方法。

m_submit.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent e) {
        submit();
        System.out.println("Test");
        butonTest.this.close();
    }
});

我不确定你想用无限循环做什么。无论如何,它会在您显示对话框之前运行完成。

了解一下事件处理在 Swing 中的工作原理会有所帮助:)

于 2014-05-18T17:36:35.653 回答
1

恐怕您的构造函数 butonTest() 和 submit() 方法不在您的类中(公共类 butonTest 扩展了 JFrame)。

你需要让他们进入你的班级:

于 2014-05-18T17:36:52.243 回答