简体   繁体   中英

Disabling a Jbutton in java when another Jbutton is pressed

My code is:

public FactoryWindow()
{
    getPreferredSize();
    setTitle("Bounce");
    JPanel buttonPanel = new JPanel();
    add(comp, BorderLayout.CENTER);
    addButton(buttonPanel, "Circle", new ActionListener()
        {
            public void actionPerformed(ActionEvent event)
            {
                comp.addShape();
            }
        });
    addButton(buttonPanel, "Machine", new ActionListener()
        {
            public void actionPerformed(ActionEvent event)
            {
                comp.addMachine();

            }
        });
    addButton(buttonPanel, "Close", new ActionListener()
        {
            public void actionPerformed(ActionEvent event)
            {
                System.exit(0);
            }
        });
    add(buttonPanel, BorderLayout.SOUTH);
    pack();
}

This is a constructor. the class extends JFrame

public void addButton(Container c, String title, ActionListener listener)
{
   JButton button = new JButton(title);
   c.add(button);
   button.addActionListener(listener);
}

I want to be able to disable the Shape button when I press the machine button

How would I go about doing that?

I know there is Something like buttonName.setEnabled(false); but I cannot figure out how to use it in this context.

You will need a reference to the button you are trying to disable, this will require you to change your code slightly...

First, you need your addButton method to return the button it created...

public JButton addButton(Container c, String title, ActionListener listener) {
    JButton button = new JButton(title);
    c.add(button);
    button.addActionListener(listener);
    return button;
}

Then you need to assign the result to a variable...

JButton cirlce = null;
JButton machine = null;

cirlce = addButton(buttonPanel, "Circle", new ActionListener() {
    public void actionPerformed(ActionEvent event) {
        comp.addShape();
    }
});

Then you can access it from your ActionListener ...

machine = addButton(buttonPanel, "Machine", new ActionListener() {
    public void actionPerformed(ActionEvent event) {
        comp.addMachine();
        circle.setEnabled(false);
    }
});

Now, if you're using Java 6 (and I think Java 7), it will complain that the button should be final , but this won't work based on the way you have your code set up. Instead, you will need to make circle and machine instance fields in order to be able to access them from within the ActionListener context

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