简体   繁体   中英

Nothing happens when a button is pressed

I am creating a program that lets user input the values of function x, snip of the code below:

JLabel f1= new JLabel (" x1 = ");
JLabel f2 = new JLabel (" x2 = ");

JButton submit = new JButton("Submit values");
submit.addActionListener(this);

JTextField x1 = new JTextField();
JTextField x2 = new JTextField();

inputPanel.add(f1);
inputPanel.add(x1);
inputPanel.add(f2);
inputPanel.add(x2);

inputPanel.add(submit);

It looks something like this:

x1 = [input field] x2 =[input field] (submit values)

My ActionPerformed method looks like this:

public void actionPerformed(ActionEvent e)
{
    if("submit".equals(e.getActionCommand()))
    {
        System.out.println("click");
    }
}

I've added the System.out.println to check if program knows when I click the submit button, but there is nothing being printed out to the console, my question is why and how do I change it?

and another thing I want to ask is how can I take the input of both x1, x2 at the same time? I understand that I will probably need an if function to check if none of the fields are blank?

Replace "submit".equals(e.getActionCommand()) with e.getSource()==submit and it should work as you are expecting.

You should explicitly set the action command for the "submit" button. Like this:

JButton submit = new JButton("Submit values");
submit.addActionListener(this);
submit.setActionCommand("submit");

Remember, you should set an action command for a Component (refers to JButton here) before it could pass the action command to the ActionEvent .

The problems is with your actionCommand.

JButton submit = new JButton("Submit values");

If you don't explicitly set an action command, it reverts to the Button text .

If your button text is too long or inconvenient to use then do the following:

submit.setActionCommand("submit");

Try declaring an anonymous inner class, this will create an action listener just for your button. Additionally this will be useful if you decide to add more buttons in the future, since you could just declare a new class for each button. Just remember to define submitButtonPressed() later.

Your code would look like this:

    JButton submit = new JButton("Submit values");
    submit.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            submitButtonPressed();
        }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM