2011-01-03 2 views
1

전함을 만들기 위해 노력하고 있습니다. 전 보드를 통제하고 있습니다. 어떻게하면 각 버튼이 위치를 반환 할 수 있도록 배열을 만들 수 있습니까? 배송 및 안타와 물건을 저장합니다. 각 개별 버튼을 만들고 싶지만 어떻게해야하는지 잘 모르겠습니다.배열에 개별 버튼 이름을 만들려면 어떻게합니까?

답변

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의 생성자에 전달합니다.

이렇게하면 Action 클래스의 clickPerformed 메소드를 오버라이드하여 버튼 클릭 이벤트가 동일한 클래스에 모두 잘 정리 된 좌표를 사용할 수있게합니다.

관련 문제