我应该为每个类似的动作或通用动作单独使用ActionListener吗? [英] Should I use separate ActionListener for each similar action or generic one?

查看:139
本文介绍了我应该为每个类似的动作或通用动作单独使用ActionListener吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用java创建一个使用按钮的键盘,当用户点击从A到Z标签的按钮时,它会将JTextField文本设置为A或按任何按钮。

I'm creating a keyboard using buttons with java, when a user clicks on a button labelled from A to Z it will set a JTextField text to A or whatever button they pressed.

我有一个单独的类为每个按钮,所以A它的 public class listenser1实现ActionListener ,B它的 public class listenser2实现ActionListener 这是一个很好的方法吗?

I have a seperate class for each button so for A its public class listenser1 implements ActionListener, B its public class listenser2 implements ActionListener is this a good way of doing it?

我也试图做一个类,并使用if和if else语句购买使用

Also I tried to do do it under one class and used if and if else statements buy using

        if(a.getText().equals("A"))
        {
           input1.setText(input.getText() + "A");       
        }
        .
        .
        .

这不起作用,它打印出ABCDEFGHIJKLMNOPQRSTUVWXYZ而不是一个字母。

And this doesn't work, it prints out ABCDEFGHIJKLMNOPQRSTUVWXYZ instead of just the one letter.

推荐答案

不,这不是最有效的方式。写得太久了。相反,请尝试:

No, that is not the most efficient way. That takes way too long to write. Instead, try this:

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;

public class Example extends JFrame implements ActionListener {
    private final String[] letters = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
    private JButton[] buttons = new JButton[26];
    private JTextArea text = new JTextArea();

    public Example() {
        super("Example");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        for (int i = 0; i < letters.length; i++) {
            buttons[i] = new JButton(letters[i]);
            buttons[i].addActionListener(this);
            add(buttons[i]);
        }
        add(text);
        pack();
        setVisible(true);
    }

    public void actionPerformed(ActionEvent event) {
        text.append(event.getActionCommand());
    }

    public static void main(String[] args) {
        Example ex = new Example();
    }
}

这篇关于我应该为每个类似的动作或通用动作单独使用ActionListener吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆