2016-06-01 3 views
2

나는 100x JButtons를 10x10 매트릭스처럼 위치하는 픽셀로 사용하여 컬러 연필 프로젝트를하고 있습니다. 나는 또한 색을 나타내는 10 개의 다른 jButton과 "연필"과 "버킷"도구를 나타내는 2 개의 다른 jButton을 가지고 있습니다.Java에서 기존 JButton을 사용하여 JButton Array를 만드는 방법은 무엇입니까?

이제 필자는 연필 jButton 만 사용하므로 연필 JButton을 클릭 한 다음 색상 JButton 중 하나를 선택하여 100 개의 JButton 중 하나를 칠할 수 있습니다.

알고리즘이 정상적으로 작동합니다. 문제는 모든 JButton에 동일한 색상 표시 방법 (colorButton)을 적용해야하므로 모든 JButton을 저장하고 각각에 대해 colorButton 메서드를 호출하도록 배열을 만들고 싶다는 것입니다. 그들의.

이미 100 개의 JButton을 JButton 배열에 저장하는 방법에 대한 단서가 없습니다.

만 JButton1보다 더 그래서 다른
public void colorButton(JButton button){ 
    if (type == "pencil"){ 
     if(color.equals("gray")){ 
      button.setBackground(new Color(101,101,101)); 
     }else if(color.equals("white")){ 
      button.setBackground(new Color(255,255,255)); 
     }else if(color.equals("black")){ 
      button.setBackground(new Color(0,0,0)); 
     }else if(color.equals("blue")){ 
      button.setBackground(new Color(0,0,255)); 
     }else if(color.equals("red")){ 
      button.setBackground(new Color(255,0,0)); 
} 

public void buttonArray(){ 
    JButton[] button = new JButton[100]; 

    for (int i = 0; i < 100; i++){ 
     button[i] = jButton1; //I need to get each of the 100 buttons here 
     colorButton(button[i]); 
    } 
} 

내가 100

어떤 생각을 모두 저장하는 방법이 필요합니다 :

이 노력하고 무엇을 임?

감사

*는 colorButton를()는 몇 누락으로 방법은 가짜 인이 사용되는지의 상황을 알고 가정하지 않고 질문 상황

+0

100 개의 요소가 포함 된 배열을 할당했지만 각 요소는 할당하지 않았습니다. 다른 말로하면,이 작업은'button [i] = new JButton'입니다. 이것은 간단한 질문이지만 쉽게 무시할 수 있습니다. –

+1

(주제 외) :'=='와 문자열 비교를하지 마십시오. 'String.equals()'를 사용해야합니다. –

+1

''이 (가) 이미 만들어져 있고 이름이 지정되어 있기 때문에. 이러지 마. for 루프에 단추를 만들고 동일한 루프 내에서 JButton 배열 또는 'ArrayList '에 할당합니다. 그런 식으로 100 개의 변수 이름을 사용하지 마십시오. 그러면 광기와 디버깅의 악몽이 생깁니다. –

답변

1

을 명확히하기 위해 편집 바지 멜빵.

다음 자바 코드는 ColorButtons 클래스에 정의 된 기존 JButton을 사용하여 리플렉션을 사용하여 ArrayList를 채 웁니다.

다른 목록으로 루프에 배열을 지정해야하는 이유는 여전히 확실치 않지만 여기에 있습니다.

public class ColorButtons { 
    // JButton sample. 
    private JButton button1 = new JButton("1"); 
    private JButton button2 = new JButton("2"); 
    private JButton button3 = new JButton("3"); 

    // This is used to store the buttons. 
    ArrayList<JButton> jbuttons = new ArrayList<JButton>(); 

    // Boilerplate, as I have no idea what this does. 
    private String type = "pencil"; 
    private String color = "white"; 

    /** 
    * Populate the JButton List on instantiation. 
    * 
    * @see ColorButtons#populateJButtonList() 
    */ 
    public ColorButtons() { 
     // Populate "jbuttons" ArrayList with JButtons. 
     this.populateJButtonList(); 
    } 

    public void colorButton(JButton button) { 
     if (type == "pencil") { 
      if (color == "gray") { 
       button.setBackground(new Color(101, 101, 101)); 
      } else if (color == "white") { 
       button.setBackground(new Color(255, 255, 255)); 
      } else if (color == "black") { 
       button.setBackground(new Color(0, 0, 0)); 
      } else if (color == "blue") { 
       button.setBackground(new Color(0, 0, 255)); 
      } else if (color == "red") { 
       button.setBackground(new Color(255, 0, 0)); 
      } 
     } 
    } 

    public void buttonArray() { 
     JButton[] button = new JButton[100]; 

     for (int i = 0; i < 100; i++) { 
      // Assign each JButton in the list to array element. 
      for (JButton jbutton : jbuttons) { 
       button[i] = jbutton; // I need to get each of the 100 buttons 
             // here 
       System.out.println("Button" + button[i].getText()); 
       colorButton(button[i]); 
      } 
     } 
    } 

    /** 
    * This is used to add the JButtons to a list using reflection. Used in the 
    * constructor. 
    * 
    * @see ColorButtons#ColorButtons() 
    */ 
    public void populateJButtonList() { 
     // Gets the class attributes, e.g. JButton, String, Integer types, everything. 
     // In this case it is this class, but can define any other class in your project. 
     Field[] fields = ColorButtons.class.getDeclaredFields(); 

     // Loop over each field to determine if it is a JButton. 
     for (Field field : fields) { 

      // If it is a JButton then add it to the list. 
      if (field.getType().equals(JButton.class)) { 
       try { 
        // De-reference the field from the object (ColorButtons) and cast it to a JButton and add it to the list. 
        jbuttons.add((JButton) field.get(this)); 
       } catch (IllegalArgumentException | IllegalAccessException 
         | SecurityException e) { 
        e.printStackTrace(); 
       } 
      } 
     } 
    } 

    public static void main(String... args) { 
     ColorButtons color = new ColorButtons(); 

     color.buttonArray(); 
    } 
} 
+0

그래, 내 방법에서 사용한 부분은 모의인데, 나머지 부분은 더 많은 색상으로 구성되어있어 전체를 복사해야한다고 생각하지 않았다.조금 명확히하기 위해, 문자열 색상과 유형은 색상을 나타내는 10 개의 jButton과 연필과 양동이의 2 가지 유형이 있으므로 클릭 한 Jbutton을 결정하는 데 사용되는 전역 변수입니다. 유형 및 색상 변수는 선택한 색상 및 도구에 따라 지정됩니다. – Devikn

+0

이미 생성 한 jButton으로 배열을 채우기 위해 리플렉션 사용을 제안 해 주셔서 감사합니다. Reflection이나 Field 객체에 익숙하지 않아 populateJButtonList 메서드가 어떻게 작동하는지 이해할 수 없으므로 향후 코드에서 올바르게 사용하기 위해 병목을 조사해야합니다. 당신이 쓴 코드를 사용해보십시오. 도움을 주셔서 감사합니다 – Devikn

+0

나는 리플렉션을 포함하는 코드가 무엇을하는지 설명하기 위해 더 많은 코멘트로 수정 중입니다. – JasonTolotta

관련 문제