简体   繁体   English

如何禁用一个按钮而不是Java Swing中的全部按钮?

[英]how to disable one button but not all in Java Swing?

I have one actionListener attached to all my Buttons. 我有一个actionListener附加到我所有的Button上。 I have 26 buttons each corresponding to one alphabet. 我有26个按钮,每个按钮对应一个字母。 After an alphabet is clicked, I want to disable that button alone. 单击一个字母后,我想单独禁用该按钮。 how can I achieve this Jwing? 我如何实现这个Jwing? I am pasting a part of code, as my entire is too long and has other details which are not necessary. 我要粘贴一部分代码,因为我的整个代码太长,并且有其他不必要的细节。 Thanks 谢谢

public DetailsPanel(GuessPane guess) {
            setLayout(new BorderLayout());
            setBorder(BorderFactory.createTitledBorder(" click here "));

            JPanel letterPanel = new JPanel(new GridLayout(0, 5));
            for (char alphabet = 'A'; alphabet <= 'Z'; alphabet++) {
                String buttonText = String.valueOf(alphabet);
                JButton letterButton = new JButton(buttonText);
                letterButton.addActionListener(clickedbutton(guess));
                letterPanel.add(letterButton, BorderLayout.CENTER);
            }
            add(letterPanel, BorderLayout.CENTER);
        }

        private ActionListener clickedbutton(final GuessPane guess) {
            return new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    JButton pressedButton = (JButton) e.getSource();
                    String actionCommand = e.getActionCommand();
                    try {
                        System.out.println("actionCommand is: ---" + actionCommand);
                        guess.setLetter(actionCommand);
                    } catch (ParseException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }

您可以使用event.getSource()获取事件的来源( notice getSource()返回一个Object因此您也需要对其进行强制转换):

((AbstractButton)event.getSource()).setEnabled(false);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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