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

时间:2013-10-19 01:46:53

标签: java swing button jbutton actionlistener

我有一个actionListener附加到我的所有按钮。我有26个按钮,每个按钮对应一个字母。单击一个字母后,我想单独禁用该按钮。我怎么能实现这个Jwing? 我正在粘贴代码的一部分,因为我的整个代码太长并且有其他不必要的细节。 感谢

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();
                    }

1 个答案:

答案 0 :(得分:1)

您可以使用event.getSource()来获取活动的来源(notice getSource()会返回Object,因此您需要将其投射到其中):

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