简体   繁体   English

使用ActionListener的Java Swing干净代码

[英]Java Swing clean code with ActionListener

I am trying to make cleaner code in my programs. 我正在尝试在程序中编写更清晰的代码。 So I was trying to compress my code to create buttons: 所以我试图压缩我的代码来创建按钮:

Before, I needed to copy this every single time: 以前,我需要每次复制一次:

Dimension JButton_Cryption_Size = JButton_Cryption.getPreferredSize();
        JButton_Cryption.setBounds(5, 5, JButton_Cryption_Size.width + 50, JButton_Cryption_Size.height);
        JButton_Cryption.setFocusPainted(false);

        JButton_Cryption.addActionListener(this);

        add(JButton_Cryption);

but now I made this method: (Don't pay attention to the button names, they are for testing) 但是现在我做了这个方法:(不用注意按钮的名称,它们只是用于测试)

public JButton  JButton_Testing1,
                    JButton_Testing2,
                    JButton_3;

    private void addJButton(JButton ButtonName, String Name, int x, int y, int width, int height, String ToolTip, boolean FocusedPainted, boolean Opaque, boolean ContentAreaFilled, boolean BorderPainted){
        ButtonName = new JButton(Name);

        Dimension Button_Size = ButtonName.getPreferredSize();
        if(width == 0){
            ButtonName.setBounds(x, y, Button_Size.width, height);
        }if(height == 0){
            ButtonName.setBounds(x, y, width, Button_Size.height);
        }if(width == 0 && height == 0){
            ButtonName.setBounds(x, y, Button_Size.width, Button_Size.height);
        }if(width != 0 && height != 0){
            ButtonName.setBounds(x, y, width, height);
        }

        ButtonName.addActionListener(this); // class: implements ActionListener

        ButtonName.setToolTipText(ToolTip);
        ButtonName.setFocusPainted(FocusedPainted);
        ButtonName.setOpaque(Opaque);
        ButtonName.setContentAreaFilled(ContentAreaFilled);
        ButtonName.setBorderPainted(BorderPainted);

        add(ButtonName);
    }

    private void addButtonToFrame(){
        addJButton(JButton_Testing1, "Testing 1", 150, 100, 172, 0, null, false, true, true, true);
        addJButton(JButton_Testing2, "Testing 2", 0, 0, 0, 0, null, false, true, true, true);
        addJButton(JButton_Testing3, "Testing 3", 200, 150, 250, 100, "YO", false, true, true, true);

    }

But when I want to add an action to the button, it wont work 但是当我想向按钮添加动作时,它将无法正常工作

@Override
    public void actionPerformed(ActionEvent e){
        Object src = e.getSource();
        if(src == JButton_Testing1){
            System.out.println("yo");
        }
    }

How can I make so I can keep my thing (or modify it a bit) so I can use the ActionListener correctly 我该如何做才能保留自己的东西(或稍作修改),以便可以正确使用ActionListener

Your question is about clean code, and you ask us to not pay attention to the button names. 您的问题是关于干净的代码,请我们不要注意按钮的名称。 Half of having clean code is about having good names. 拥有清晰代码的一半是关于拥有好名声的。 Respect the Java conventions, and assign meaningful names to your variables and methods. 遵守Java约定,并为变量和方法分配有意义的名称。 Variables and methods start with a lowercase character in Java. 变量和方法在Java中以小写字母开头。 And they don't contain underscores. 而且它们不包含下划线。

Also, Swing has layout managers. 此外,Swing具有布局管理器。 Stop setting bounds. 停止设置边界。 Use layout managers. 使用布局管理器。

Avoid having methods with 11 parameters. 避免使用带有11个参数的方法。

Avoid having public fields. 避免有公共场所。 Fields should be private. 字段应为私有。

And finally, don't use this as the action listener. 最后,不要将this用作动作侦听器。 Use a separate class as your listener. 使用单独的类作为您的侦听器。

Regarding your problem: your addJButton() method doesn't add a listener to the button passed as argument. 关于您的问题:您的addJButton()方法不会向作为参数传递的按钮添加侦听器。 It ignores this argument, creates a new button, and adds the listener to this new button: 它忽略此参数,创建一个新按钮,并将侦听器添加到此新按钮:

public void addJButton(JButton ButtonName, ...) {
    ButtonName = new JButton(Name);

A bad strategy is also the addButtonToFrame() method. 一个糟糕的策略也是addButtonToFrame()方法。 It hard codes the number of buttons, their names, and everything. 它对按钮的数量,它们的名称以及所有内容进行硬编码。 This way if you want to add one more button (for any reason) you have to write one more (custom) line of code to this method. 这样,如果您想(出于任何原因)再添加一个按钮,则必须为此方法再编写一行(自定义)代码。 The right way here is to make an addButtonToFrame(ArrayList <Button> buttons) method. 正确的方法是制作一个addButtonToFrame(ArrayList <Button> buttons)方法。 You pass an ArrayList of (as many as you please) buttons in this method. 您在此方法中传递了一个ArrayList (按您的喜好)。 Then add them in the panel, given the objects have been created with Dimension parameter. 假定已使用Dimension参数创建了对象,然后将它们添加到面板中。

But again, this is kind of making a new layout manager, and java has some really nice layout managers. 但是,这又是一个新的布局管理器,而java有一些非常好的布局管理器。 In other words you are reinventing the wheel. 换句话说,您正在重新发明轮子。 That is not always bad (it is a good practice), but to make a good manager you have to spend time and (as I said) there are good managers. 这并不总是不好的(这是一种好习惯),但是要成为一名好的经理,您必须花时间,而且(如我所说)要有好的经理。

Example: 例:

class ButtonExample{
    ArrayList <JButton> buttons = new ArrayList<JButton>();
    ActionListener beh = new ButtonEventHandler()    //this is a custom class that contains actionPerformed() method

    createButtons(){
        for (int i = 0; i < buttons.size(); i++)
            buttons.get(i) = new JButton();
    }

    addListeners(){
        for (int i = 0; i < buttons.size(); i++)
            buttons.get(i).addActionListener(beh);
    }

}

The ArrayList is a kind of array without standard size. ArrayList是一种没有标准大小的数组。 It is implemented using some nice tricks (that there is no need to know to use it) and you can access its objects with get() method (instead of [] operator like in regular arrays) 它使用一些不错的技巧(不需要使用它)实现,并且可以使用get()方法(而不是像常规数组中的[]运算符)访问其对象。

The addListeners() and createButtons() methods are dummies just to see how ArrayLists work. addListeners()和createButtons()方法是傻瓜,只是为了了解ArrayLists是如何工作的。 You can pass them as parameters in other methods the way you pass any regular object. 您可以像传递任何常规对象一样,以其他方法将它们作为参数传递。

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

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