0

我的所有按钮都附加了一个 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();
                    }
4

1 回答 1

1

您可以使用以下方法获取事件的来源event.getSource()(并notice getSource()返回 an Object,因此您还需要对其进行转换):

((AbstractButton)event.getSource()).setEnabled(false);
于 2013-10-19T01:58:49.160 回答