Synergy76
Synergy76

Reputation: 31

Make a method be able to take two different types as parameters

I'm working on a project and I'm getting kind of tired of writing .sets constantly, so I was going to make a few methods to abbreviate the code and make it quicker. I'm using JButtons, JLabels, and JTextFields, is there a way I could write a method to have the ability to .setInvisible(false); on any of these? Or do I have to have separate methods for each type. Thank you!

Example:

public void siv((JButton || JLabel || JTextField) input) {
input.setVisible(false);
}

***Edit: Just to be clear I'm trying to see if there is a way Java can understand to take the one entered as opposed to needing all three. I'm trying to find a way to do this without doing what I've added below:

private void siv(JButton input, JTextField input2, JLabel input3) {
    input.setVisible(false);
    input2.setVisible(false);
    input3.setVisible(false);
}

Upvotes: 0

Views: 69

Answers (1)

Sleiman Jneidi
Sleiman Jneidi

Reputation: 23329

JButton, JTextField, and JLabel inherit from JComponent which has the method setVisible, so you can have a method that takes an array of JComponent and sets their visibilities.

 public void setVisibility(boolean visibility, JComponent... components) {
   for(JComponent component: components){ 
     component.setVisible(visibility);
   }
 }

Upvotes: 6

Related Questions