2010-05-27 2 views
1

hw 지정의 경우 스윙을 익히고 이벤트에 응답하는 사용자 정의 버튼을 작성해야했습니다. 우리는 또한이 버튼을 나를 혼란스럽게하는 이벤트 소스로 만들려고했습니다. 내 CustomButton을 수신 대기하도록 등록 할 청취자를 추적하는 ArrayList가 있습니다. 내가 혼란스러워하는 것은 청취자에게 어떻게 알리는 것입니다. 선생님은 알리고 우선 순위가 높은 actionPerformed를 가졌음을 암시했지만, 생성자 문서를보고 ActionEvent 객체를 만드는 방법을 알지 못했습니다. 근원, 이드, 문자열이 모두 나를 혼란스럽게합니다. 어떤 도움을 주시면 감사하겠습니다.Java의 CustomButton에 대한 ActionEvent 객체 만들기

코드 : ActionEvent

import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 
import java.util.List; 
import java.util.ArrayList; 

public class CustomButton 
{ 
    public static void main(String[] args) 
    { 
     EventQueue.invokeLater(new Runnable() 
     { 
      public void run() 
      { 
       CustomButtonFrame frame = new CustomButtonFrame(); 
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
       frame.setVisible(true); 
      } 
     }); 
    } 

    public void addActionListener(ActionListener al) 
    { 
     listenerList.add(al); 
    } 

    public void removeActionListener(ActionListener al) 
    { 
     listenerList.remove(al); 
    } 

    public void actionPerformed(ActionEvent e) 
    { 
     System.out.println("Button Clicked!"); 
    } 

    private void notifyListeners() 
    { 
     ActionEvent event = new ActionEvent(CONFUSED HERE!!!!; 
     for (ActionListener action : listenerList) { 
      action.actionPerfomed(event); 
     } 
    } 

    List<ActionListener> listenerList = new ArrayList<ActionListener>(); 
} 

class CustomButtonFrame extends JFrame 
{ 
    // constructor for CustomButtonFrame 
    public CustomButtonFrame() 
    { 
     setTitle("Custom Button"); 
     CustomButtonSetup buttonSetup = new CustomButtonSetup(); 
     this.add(buttonSetup); 
     this.pack(); 
    } 
} 

class CustomButtonSetup extends JComponent 
{ 
    public CustomButtonSetup() 
    { 
     ButtonAction buttonClicked = new ButtonAction(); 
     this.addMouseListener(buttonClicked); 
    } 

    // because frame includes borders and insets, use this method 
    public Dimension getPreferredSize() 
    { 
     return new Dimension(200, 200); 
    } 

    public void paintComponent(Graphics g) 
    { 
     Graphics2D g2 = (Graphics2D) g; 

     // first triangle coords 
     int x[] = new int[TRIANGLE_SIDES]; 
     int y[] = new int[TRIANGLE_SIDES]; 
     x[0] = 0; y[0] = 0; 
     x[1] = 200; y[1] = 0; 
     x[2] = 0; y[2] = 200; 
     Polygon firstTriangle = new Polygon(x, y, TRIANGLE_SIDES); 

     // second triangle coords 
     x[0] = 0; y[0] = 200;  
     x[1] = 200; y[1] = 200; 
     x[2] = 200; y[2] = 0; 
     Polygon secondTriangle = new Polygon(x, y, TRIANGLE_SIDES); 

     g2.drawPolygon(firstTriangle); 
     g2.setColor(firstColor); 
     g2.fillPolygon(firstTriangle); 

     g2.drawPolygon(secondTriangle); 
     g2.setColor(secondColor); 
     g2.fillPolygon(secondTriangle); 

     // draw rectangle 10 pixels off border 
     int s1[] = new int[RECT_SIDES]; 
     int s2[] = new int[RECT_SIDES]; 
     s1[0] = 5; s2[0] = 5; 
     s1[1] = 195; s2[1] = 5; 
     s1[2] = 195; s2[2] = 195; 
     s1[3] = 5; s2[3] = 195; 
     Polygon rectangle = new Polygon(s1, s2, RECT_SIDES); 
     g2.drawPolygon(rectangle); 
     g2.setColor(thirdColor); 
     g2.fillPolygon(rectangle); 
    } 

    private class ButtonAction implements MouseListener { 
     public void mousePressed(MouseEvent e) 
     { 
      System.out.println("Click!"); 
      firstColor = Color.GRAY; 
      secondColor = Color.WHITE; 

      repaint(); 
     } 

     public void mouseReleased(MouseEvent e) 
     { 
      System.out.println("Released!"); 
      firstColor = Color.WHITE; 
      secondColor = Color.GRAY; 
      repaint(); 
     } 

     public void mouseEntered(MouseEvent e) 
     {} 

     public void mouseExited(MouseEvent e) 
     {} 

     public void mouseClicked(MouseEvent e) 
     {} 
    } 

    public static final int TRIANGLE_SIDES = 3; 
    public static final int RECT_SIDES = 4; 
    private Color firstColor = Color.WHITE; 
    private Color secondColor = Color.DARK_GRAY; 
    private Color thirdColor = Color.LIGHT_GRAY; 
} 

답변

1

일반적인 생각은 :

  • 당신은 청취자의 컬렉션을 유지합니다.
  • 리스너 (이벤트가 발생 함)에 통지해야하는 경우 리스너 컬렉션을 반복하고 각 리스너 (사용자의 경우에는 ActionListener)에서 적절한 메소드를 호출합니다.

ActionListener 및 ActionEvent의 선언이 표시되지 않습니다. 패턴을 사용하면 ActionEvent에는 실제 이벤트를 나타내는 일종의 status 필드가있을 가능성이 높으므로 public ActionEvent(int value) 정도의 생성자가 있습니다. 청취자는 ActionEvent를 수신하고, ActionEvent 객체를 조사하고, 그가 통지 된 이유를 알립니다. 다른 사람에서

편집

난 그냥 된 ActionListener와의 ActionEvent가 AWT 클래스입니다 것을 알게 대답합니다. 그래서 그들의 자바 문서를보고, 내 대답의 나머지는 여전히 유효해야합니다.

편집 2

가장 쉬운 생성자이 하나입니다

source
public ActionEvent(Object source, int id, String command); 

은 대부분, 귀하의 경우, 그래서 버튼을 이벤트를 발생시킨 객체입니다. id은 이벤트 유형을 식별합니다. ActionEvent 또는 AWTEvent의 정적 필드에서 선택하십시오. 명령은 이벤트와 관련된 추가 정보를 입력 할 수있는 영역입니다.

+0

ActionEvent는'awt' 패키지의 표준 클래스입니다. – Roman

1

읽기 문서. 생성자에 대한 섹션이 있으며 각 매개 변수가 의미하는 것을 읽습니다. 귀하의 경우를 들어

appliable 코드는 다음과 같이 될 것입니다 :

int uniqueId = System.currentTimeMillis().intValue(); 
String commandName = ""; //it can be like "show" or "hide" or whatever else; 
         //you can get this string with getActionCommand() method 
         //and make some actions based on its value 
         //... but you don't need it now 
ActionEvent event = new ActionEvent(this, uniqueId, commandName); 
+2

고유 ID는 확실합니까? 'ActionEvent.ACTION_FIRST'와 같이 정의 된 id를 사용해야하지 않습니까? –

+0

@Andreas_D : 아니요, 확실하지 않습니다. 그것은 아마도 상황에 달려 있습니다. OP는 마우스 이벤트를 처리하여 자신의 버튼을 생성하므로 ActionEvent 클래스를 사용할 필요조차 없습니다. 그는 필요한 자질을 가지고 자신 만의 것을 만들 수 있습니다. – Roman

+0

나는 하나 된 uniqueID과의 ActionEvent이 방법을 생성하고, ""문자열, 나는 여전히 오류 얻을 시도 : rivate 무효 notifyListeners() \t { \t \t INT UNIQUEID = 0; \t \t ActionEvent 이벤트 = 새 ActionEvent (this, uniqueId, ""); (ActionListener를 조치 : listenerList) 용 \t \t \t \t { \t action.actionPerfomed (이벤트); \t \t} \t} – Crystal