سؤال

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

هل كانت مفيدة؟

المحلول 2

A bad strategy is also the addButtonToFrame() method. 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. You pass an ArrayList of (as many as you please) buttons in this method. Then add them in the panel, given the objects have been created with Dimension parameter.

But again, this is kind of making a new layout manager, and java has some really nice layout managers. 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. 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)

The addListeners() and createButtons() methods are dummies just to see how ArrayLists work. You can pass them as parameters in other methods the way you pass any regular object.

نصائح أخرى

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. Variables and methods start with a lowercase character in Java. And they don't contain underscores.

Also, Swing has layout managers. Stop setting bounds. Use layout managers.

Avoid having methods with 11 parameters.

Avoid having public fields. Fields should be private.

And finally, don't use this as the action listener. Use a separate class as your listener.

Regarding your problem: your addJButton() method doesn't add a listener to the button passed as argument. 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);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top