Search code examples
javanetbeansjbutton

Is it possible to use component (like jButton) as an argument in a function?


If I am using the exact same lines of code for multiple buttons, can I use a component (in this case button) as an argument for a function instead of using a variable? That will make my work so much easier. If I have something like this:

a1.setText("something");
a1.setBackground(Color.BLACK);
a1.setForeground(Color.WHITE);

a2.setText("something");
a2.setBackground(Color.BLACK);
a2.setForeground(Color.WHITE);

a3.setText("something");
a3.setBackground(Color.BLACK);
a3.setForeground(Color.WHITE);

Can I make them into one function something like:

public void buttonFunction(Button something){
    something.setText("something");
    something.setBackground(Color.BLACK);
    something.setForeground(Color.WHITE);
}

If I can, how can I?


Solution

  • It is. The attempt you made is the way to do this.

    public void buttonFunction(JButton something){
        something.setText("something");
        something.setBackground(Color.BLACK);
        something.setForeground(Color.WHITE);
    }
    

    All you need to do is call this function after you created the JButton objects.