简体   繁体   中英

How to make a JButton unclickable after clicking on it?

Here's my code :

for(int row = 0; row < 10; row++)
{
    for(int col = 0; col < 10; col++)
    {
            button = new JButton();

            panel_1.add(button);
     }
 }

    button.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent e)
        {
            //If Button is clicked, make the button unclickable
            if(button == (JButton)e.getSource())
            {
                button.setEnabled(false);

            }
        }

    });

I want to make any JButton I click from this 10 x 10 grid button layout unclickable; however, this method only makes no other that the right button unclickable, What's wrong? I have put the ActionListener outside the for-Loop that is responsible for making the buttons. I don't know what's going on.

Here's what it looks like :

在此处输入图片说明

Edit: bsd code works. Add ActionListener before adding the buttons or something along those lines.

You only add the ActionListener to the last button created.

You need to add the ActionListener to every button created inside the loop.

So the code should be something like:

ActionListener al = new ActionListener()
{
    public void actionPerformed(ActionEvent e)
    {
         JButton button = (JButton)e.getSource();
         button.setEnabled( false );
    }
};

for(int row = 0; row < 10; row++)
{
    for(int col = 0; col < 10; col++)
    {
            button = new JButton();
            button.addActionListener( al );
            panel_1.add(button);
     }
 }

Since you want to disable all buttons in your panel. The button action listener should be inside the for loop.

button = new JButton();
button.addActionListener(new ActionListener()
{
    public void actionPerformed(ActionEvent e)
    {
        //If Button is clicked, make the button unclickable
        if(button == (JButton)e.getSource())
        {
            button.setEnabled(false);

        }
    }

});

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