有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java JButton打印一封信

如何打印用户单击的按钮的字母,然后禁用该按钮

我使用for循环生成每个字母的按钮

   } for (int i = 65; i <= 90; i++) {
        btnLetters = new JButton(" " + (char) i);
        letterJPanel.add(btnLetters);
        letterJPanel.setLayout(new FlowLayout());
        btnLetters.addActionListener(this);

    }

单击按钮时,应打印字母,然后禁用按钮

public void actionPerformed(ActionEvent ae) {

    if (ae.getSource() == btnLetters) {

    }
}

共 (4) 个答案

  1. # 1 楼答案

    if (ae.getSource() == btnLetters) { } }
    

    这部分只适用于创建的最后一个按钮,因此我认为它是无意义的。

    最好做那样的事

    if (ae.getSource() instance of JButton &&
        ((JButton ) ae.getSource()).getText().length()==2) {
        PRINT(((JButton ) ae.getSource()).getText().substring(1));
        ((JButton ) ae.getSource()).setEnabled(false);
    }
    

    其中“打印”是实际打印(无论如何)

  2. # 2 楼答案

    创建一个新类

    public class ButtonDisabler implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            JButton button = (JButton)e.getSource();
            System.out.println(button.getText() + " pressed");
            button.setEnabled(false);
        }
    }
    

    然后将其添加到每个按钮

    btnLetters.addActionListener(new ButtonDisabler());
    
  3. # 3 楼答案

    也许使用内部类会更容易

    创建按钮时

    JButton button = new JButton("A");
    button.addActionListener(new ActionListener(
        public void actionPerformed(ActionEvent e){
          printMethod(button.getLabel()); //You have to implement this...
          this.disable()
    });
    
  4. # 4 楼答案

    首先,我会这样做: (看起来比从整数中转换要好得多)

    for(char c = 'A'; c <= 'Z'; c++)
    {
        button.setText(""+c);
        ...
    }
    

    然后

    public void actionPerformed(ActionEvent ae) 
    {
        //assuming you only set the action for the JButtons with letters
        JButton button = (JButton) ae.getSource();
        String letter = button.getText();
        print(letter); //for example System.out.println();
        button.setEnabled(false);
    }