Java 可以在函数中使用组件(如jButton)作为参数吗?

Java 可以在函数中使用组件(如jButton)作为参数吗?,java,netbeans,jbutton,Java,Netbeans,Jbutton,如果我对多个按钮使用完全相同的代码行,我可以使用组件(在本例中为按钮)作为函数的参数,而不是使用变量吗?那会让我的工作轻松多了。如果我有这样的东西: a1.setText("something"); a1.setBackground(Color.BLACK); a1.setForeground(Color.WHITE); a2.setText("something"); a2.setBackground(Color.BLACK); a2.setForeground(Color.WHITE);

如果我对多个按钮使用完全相同的代码行,我可以使用组件(在本例中为按钮)作为函数的参数,而不是使用变量吗?那会让我的工作轻松多了。如果我有这样的东西:

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);
我能把它们变成一个函数吗

public void buttonFunction(Button something){
    something.setText("something");
    something.setBackground(Color.BLACK);
    something.setForeground(Color.WHITE);
}
如果我能,我怎么能?

是的。 你所做的尝试就是这样做的

public void buttonFunction(JButton something){
    something.setText("something");
    something.setBackground(Color.BLACK);
    something.setForeground(Color.WHITE);
}
创建JButton对象后,只需调用此函数。

当然可以。 您可以将任何内容作为参数传递,即使是方法、类和类型

1.这里有一个简单的方法可以满足您的要求:

public static Component setUpComponent(Component component){
    if(component instanceof JButton){
        JButton button = (JButton)component;
        button.setText("something");
        button.setBackground(Color.BLACK);
        button.setForeground(Color.WHITE);
        return button;
    } else if(component instanceof <"Some other class, like JPanel">){
       //do something else for that class
    }
    throw new Exception("Invalid Object");
    return null;
}
以下是如何使用此功能:

for(int index = 0; index <= 2; index++){
    JButton button = new JButton();
    setUpComponent(button);
    //do whatever you want to do
}
for(int index = 0; index <= 2; index++){
    JButton button = setUpComponent(button);
    //do whatever you want to do
}
for(int index = 0; index <= 2; index++){
    JButton button = new CustomButton();
    //same as:
    //CustomButton button = new CustomButton();
    //or
    //JButton button = new CustomButton("something",Color.BLACK,Color.WHITE);
}
以下是如何使用此功能:

for(int index = 0; index <= 2; index++){
    JButton button = new JButton();
    setUpComponent(button);
    //do whatever you want to do
}
for(int index = 0; index <= 2; index++){
    JButton button = setUpComponent(button);
    //do whatever you want to do
}
for(int index = 0; index <= 2; index++){
    JButton button = new CustomButton();
    //same as:
    //CustomButton button = new CustomButton();
    //or
    //JButton button = new CustomButton("something",Color.BLACK,Color.WHITE);
}

for(int index=0;index是的,您可以。只需像常规函数一样调用它。请注意Swing不是线程安全的;这必须在EDT.Re上完成,“我可以将它们变成一个函数吗…”尝试时发生了什么?