创建具有 Button 组件的应用程序

以下过程解释了如何在创作时将 Button 组件添加到应用程序。在此示例中,单击 Button 时会更改 ColorPicker 组件的状态。

创建具有 Button 组件的应用程序:

  1. 创建一个新的 Flash 文件 (ActionScript 3.0) 文档。
  2. 将一个 Button 组件从"组件"面板拖到舞台上,并在"属性"检查器中为该组件输入以下值:
    • 输入实例名称 aButton
    • 为 label 参数输入 Show
  3. 在舞台上添加 ColorPicker,并为它指定实例名称 aCp
  4. 打开"动作"面板,在主时间轴中选择第 1 帧,然后输入以下 ActionScript 代码:
    aCp.visible = false;
    
    aButton.addEventListener(MouseEvent.CLICK, clickHandler);
    
    function clickHandler(event:MouseEvent):void {
        
        switch(event.currentTarget.label) {
            case "Show":
                aCp.visible = true;
                aButton.label = "Disable";
                break;
            case "Disable":
                aCp.enabled = false;
                aButton.label = "Enable";
                break;
            case "Enable":
                aCp.enabled = true;
                aButton.label = "Hide";
                break;
            case "Hide":
                aCp.visible = false;
                aButton.label = "Show";
                break;
        }  
    }
    

    第二行代码将函数 clickHandler() 注册为 MouseEvent.CLICK 事件的事件处理函数。用户单击 Button 时,事件将发生,从而使 clickHandler() 函数根据 Button 的值执行以下操作之一:

    • Show 使 ColorPicker 可见,并将 Button 的标签更改为 Disable。
    • Disable 禁用 ColorPicker,并将 Button 的标签更改为 Enable。
    • Enable 启用 ColorPicker,并将 Button 的标签更改为 Hide。
    • Hide 使 ColorPicker 不可见,并将 Button 的标签更改为 Show。
  5. 选择"控制">"测试影片",运行应用程序。

以下过程使用 ActionScript 创建一个切换 Button,并且当单击该 Button 时在"输出"面板中显示事件类型。该示例通过调用类的构造函数创建一个 Button 实例,并通过调用 addChild() 方法将该实例添加到舞台上。

使用 ActionScript 代码创建 Button:

  1. 创建一个新的 Flash 文件 (ActionScript 3.0) 文档。
  2. 将 Button 组件从"组件"面板拖到当前文档的"库"面板中。

    此操作将组件添加到库中,但不会在应用程序中显示它。

  3. 打开"动作"面板,在主时间轴中选择第 1 帧,然后输入以下代码创建一个 Button 实例:
    import fl.controls.Button;
    
    var aButton:Button = new Button();
    addChild(aButton);
    aButton.label = "Click me";
    aButton.toggle =  true; 
    aButton.move(50, 50);
    

    move() 方法将按钮放在舞台的 50(x 坐标), 50(y 坐标)位置。

  4. 现在,添加以下 ActionScript 来创建一个事件侦听器和一个事件处理函数:
    aButton.addEventListener(MouseEvent.CLICK, clickHandler);
    
    function clickHandler(event:MouseEvent):void {
        trace("Event type: " + event.type);  
    }
    
  5. 选择"控制">"测试影片"。

单击按钮时,Flash 会在"输出"面板中显示消息"事件类型: 单击"。