2016-10-09 1 views
-1

複数のボタンに同じコード行を使用している場合は、変数を使用する代わりに関数の引数としてコンポーネント(この場合はボタン)を使用できますか?それは私の仕事をはるかに容易にします。私はこのような何かを持っている場合:jButtonのようなコンポーネントを関数の引数として使用できますか?

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); 
} 

私ができるならば、どのように私はできますか?

+0

はい、できます。通常の関数のように呼び出すだけです。スイングはスレッドセーフではないので注意してください。これはEDTで行う必要があります。 – markspace

+3

Re、「私はそれらを1つの機能にすることはできますか?」あなたがそれをしたとき何が起こったのですか? –

答えて

1

です。 これを行う方法があなたの試みです。

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

JButtonオブジェクトを作成した後にこの関数を呼び出すだけで十分です。

0

もちろん、それが動作することができます。 メソッド、クラス、型のいずれでもパラメータとして何かを渡すことができます。ここで

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 
} 

2.ます。また、作成することができます単にあなたに準備ができているメソッドを提供しています。

ここ

は、あなたがこれを使用することができる方法です。

for(int index = 0; index <= 2; index++){ 
    JButton button = setUpComponent(button); 
    //do whatever you want to do 
} 

3.しかし、これについて移動する最良の方法私の意見では

は、新しいクラスや設定がボタンを作成することです。そうのような:ここで

public class CustomButton extends JButton{ 

    public CustomButton(){ 
     this("something",Color.BLACK,Color.WHITE); 
    } 

    public CustomButton(String text, Color backColor, Color frontColor){ 
     super(something); 
     setBackground(backColor); 
     setForeground(frontColor); 
    } 

} 

は、あなたがこれを使用することができる方法です。

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); 
} 
関連する問題