2011-12-04 2 views
0

나는 JButton의 배열을 가지고눌려진 버튼의 이름은 무엇입니까? (???? == e.getSource())

for(i=0;i<button.length;i++) 

100 개 버튼을 생성하지만, 즉 e.getSource()처럼 넣어 무엇을 알아낼 수 없습니다 {} 무엇에 넣어야합니까? 즉, e.getSource의 경우 배열에 만들어진 버튼의 이름이 무엇인지 찾는 방법은 무엇입니까? 루프 버튼 배열을 통해

import javax.swing.*; 
import javax.swing.border.Border; 
import java.awt.Color; 
import java.awt.Font; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.util.ArrayList; 
import java.awt.*; 
import java.awt.event.*; 

public class map { 
    static int i; 
    JFrame frame = new JFrame("D&D"); 
    public map() { 
     int a=0,b=50; 
     JFrame.setDefaultLookAndFeelDecorated(true); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setBounds(100,0,1000,600); 
     frame.getContentPane().setLayout(null);  
     frame.setVisible(true); 
     frame.setBackground(Color.black); 
     frame.setResizable(false); 
     for(i=0;i<button.length;i++){ 
      a=a+50; 
      if(a>549) { 
       b=b+50; 
       a=50; 
      } 
      button[i]= new JButton(SD); 
      frame.getContentPane().add(button[i]); 
      button[i].setBounds(a, b, 50,50); 
      button[i].setFont(new Font("Blackmoor Let", Font.BOLD, 30)); 
      button[i].setForeground(Color.red); 
      button[i].setBorder(border); 
      button[i].addActionListener(boardListener); 
     } 
    } 

    ActionListener boardListener = new ActionListener(){ 
     public void actionPerformed(ActionEvent e){ 
      System.out.print("\n" +e.getSource());    
      if (e.getSource()==button[i]){    
       System.out.println("hi"); 
      } 
     } 
    }; 

    public static void main(String[]args){ 
     new map(); 
    } 
} 
+2

들여 쓰기에 이상한 형태의 코드는 무엇입니까? 그것은 정신 분열증입니까? BTW -하지 말아야 할 2 가지 사항 1)'frame.setBounds (10001000600);'컴포넌트가 일단 추가되면'pack() '을 호출하여 자식을 표시하는 데 필요한 자연적인 크기를 가정 할 수있게합니다. . 2) 'frame.getContentPane(). setLayout (null); ** 레이아웃 사용 ** –

+0

'button [i] .setFont (새 글꼴 ("Courior", Font.BOLD, 30));'(폴 라이트 기침) 맞춤법 검사! –

+0

사실, 이제 나는 그 끔찍한 코드 형식을 문제의 핵심으로 보았습니다. 글꼴이 "Courior"또는 "Courier"가 아니라 "Courier New"인 것으로 보입니다. JRE는 마법으로 글꼴을 찾지 않지만 정확한 이름을 부여합니다. ;) –

답변

2

를 사용하여 버튼을 누른 상태에서 클릭 된 버튼의 인덱스를 알고

int index = listOfButtons.indexOf(e.getSource()) 

를 사용합니다. 당신이 만들 때

List<JButton> listOfButtons = new ArrayList<JButton>(100); 
for (int i = 0; i < 100; i++) { 
    JButton button = ...;   
    listOfButtons.add(button); 
} 

당신이 (하지만 여기에 필요하지 않은 것)를 List<JButton>에 JButton의 배열을 변환 할 경우에, 다만

List<JButton> listOfButtons = Arrays.asList(buttons); 
+0

JButton button [] = 새로운 JButton [100]; { \t 새로운 ArrayList를 피곤했습니다. (Arrays.asList (array)); \t}하지만 작동하지 않는 사람이 나를 도울 수 있습니까? –

+0

@ user1078803 : 나중에 목록으로 변환하려면 배열을 만들 필요가 없습니다. 처음부터 목록을 사용하십시오. 새로운 ArrayList를 만들 필요가 없습니다. Arrays.asList (array)로 충분합니다. 내 편집 된 답변보기 –

+0

정말 고마워, 이것에 대한 답변을 만들어 자신 만의 JButton 버튼 = ... (the ...)과 eclipse는 타입 목록이 일반적이지 않다는 것을 알려준다. 인수로 매개 변수화 할 수 없습니다. , 어떻게해야합니까? 피.나는 지금까지리스트를 들어 본 적이 없기 때문에 모든 것을 자세히 설명해주었습니다. 감사합니다. –

2

하십시오 List<JButton>보다는 JButton[]

for (int i = 0; i < button.length; ++i) { 
    if (e.getSource()==button[i]);{ 
     System.out.println("Button " + i + " pressed"); 
    } 
} 
1

를 사용

목록을 작성하고 채우려면 귀하의 버튼을 시도해보십시오 :

button[i].setActionCommand(i); 

그리고 ActionEven을 시도하면 :

e.getActionCommand(); 

getActionCommand() 메소드는 i를 문자열로 반환하므로 i를 int로 구문 분석해야합니다.

관련 문제