2011-01-03 7 views

答えて

2

あなたは、ボタンクラスを拡張できます。

public class BattleShipButton extends JButton { 

    private Coordinate coords; 
    public BattleShipButton(Coordinates coords) { 
     this.coords = coords; 
     setPreferredSize(new Dimension(20, 20)); 
    } 
    public Coordinates getCoordinates() { 
     return coords; 
    } 
} 

その後、あなたは、ループ内のボタンをインスタンス化し、正しい座標に渡すことができます。

各ボタンは、getCoordiantes()を使用して取得できる正しい座標を持ちます。

+0

JButtonは、おそらく画面上の位置を保持する属性を持っています。 – Seva

+0

@Alan、正しいですが、 'getLocation()'や 'getLocationOnScreen()'を使うことができますが、これはピクセル座標を与えるだけです。これはあなたに論理的な戦艦の座標を与えるでしょう。 – jjnguy

+0

ありがとうございました:) – matt

0

ちょうど彼らの位置、インデックスを知りたい場合は、マトリックスでそれらを行う、十分でなければなりません。あなたがしたい、より具体的にした場合、あなたはあなた自身のボタンを作成してから返す機能を持たせることができ

、その位置

0

ちょうど、これはあなたを助けることが何もない よりも良いことができていない場合、私は、フォームアプリケーションは行く使用しました先に私がボタンのクリックイベント:)

をキャッチするイベントを作成する必要があるでしょう、これらのコードの後に​​、この

Button[] Barray = new Button[32,32]; 

than you will have to fill this array 

for (int i = 0; i <= a - 1; i++) 
{ 

for (int j = 0; j <= b - 1; j++) 
     { 
    Barray (i, j) = new Button(); // here you create a dynamic button 

     Barray (i, j).Location = new System.Drawing.Point(x, y); // here you locate the button in to your box or in a similar container 

     Barray (i, j).Size = new System.Drawing.Point(23, 23); // in this line you resize your button 

     Barray (i, j).Name = i + j; // in this lie you rename your button so that you will be able to reach your button and know what is its location 
     Barray (i, j).Click += Button_Click; // in this line you will add the button_click event to your dynamic buttons 
     Form1.box.Controls.Add(dizi(i, j)); // and this line adds your button to your container 
     x += 23; // in this line i am increasing the x location so i the buttons will not be placed at the same x location 
    } 
    x = 0; // this line i ll make x zero that means i m finis previous line and i ll start to place buttons on another line 
    y += 23; // this line i m increasing the y location to move the next line 
} 

のような配列を作成することができ

見てみましょう

private void button_Click(object sender, System.Windows.Forms.MouseEventArgs e) 
{ 
//here you can use e eventargs reach your buttons name so you can do anything you want :) 
} 

希望は、これはあなた

+0

質問でC#をどこで見たのですか? – adamax

0

はAbstractActionを拡張する新しいクラスを作成するのに役立ちます。ボタンの作成時に座標の属性を与え、新しいインスタンスを作成し、JButtonのコンストラクターに渡します。

このようにすると、アクションのactionPerformedメソッドをオーバーライドして、ボタンクリックイベントが同じクラスにすべて適切にパッケージ化された座標を使用できるようになります。

関連する問題