![]() |
|
||||||||||
|
|||||
|
[+4 29.10.08]
[+4 31.10.08] Регистрация: Jan 2008
Сообщений: 38
|
Появилась задача сгенерировать список кадров ролика с возможностью переходить к выбранному. Список создаётся на основе многомерного массива в котором указан номер кадра, название и другие данные относящиеся к содержимому кадра. Т.к. до этого подобным не занимался то решил разобраться на простом примере из сборника рецептов ActionScript 3.0, но пример хоть ошибок не выдаёт кнопку тоже не показывает. Если кто в этом разбирается скажите в чём ошибка и как она исправляется.
![]() Код вписан в верхний слой первого кадра: import flash.display.*;
import flash.events.*;
function SimpleButtonDemo() {
// Создаем простую кнопку и задаем ее местоположение
var button2:SimpleButton = new SimpleButton();
button2.x = 100;
button2.y = 100;
// Создаем разные состояния кнопки.
// Используя вспомогательный метод,
// создаем круги разных цветов
button2.upState = createCircle(0x00FF00, 90);
button2.overState = createCircle( 0xFFFFFF, 16 );
button2.downState = createCircle( 0xCCCCCC, 15 );
button2.hitTestState = button2.upState;
// Добавляем слушатель события click, чтобы знать,
// когда пользователь щелкает кнопку мыши
button2.addEventListener( MouseEvent.CLICK, handleClick );
// Наконец, добавляем кнопку з список отображения
addChild(button2);
}
// Вспомогательная функция для создания круга
// заданного цвета и радиуса
function createCircle( color:uint, radius:Number ):Shape {
var circle:Shape = new Shape();
circle.graphics.lineStyle( 1, 0x000000 );
circle.graphics.beginFill( color );
circle.graphics.drawCircle( 0, 0, radius );
circle.graphics.endFill();
return circle;
}
// Обработчик события, вызываемый при нажатии кнопки
function handleClick( event:MouseEvent ):void {
trace( "Мышь щелкнула по кнопке" );
}
![]() |
|
|||||
|
Регистрация: Jul 2008
Адрес: Рига
Сообщений: 176
|
Это всего лишь отрезок кода, пример реализации описанного в книге, а не полный рабочий код вашего документа.
Там даже класс не описан! Он не может не выдавать ошибок, т.к. если его вставить в [anyname].as, и указать anyname как Docuemnt class (надеюсь вы понимаете о чем я), вы удидвитесь количеству ошибок. Учите флэш с самого начала, а не с рецептов. |
|
|||||
|
Регистрация: Jan 2008
Сообщений: 28
|
Судя по коду ваша функция SimpleButtonDemo() - это конструктор класса SimpleButtonDemo, который наследует MovieClip или Sprite.
Создайте его, засуньте туда весь код, приведенный выше, назначте этот класс главным классом документа и оно будет работать. Примерно так: |
|
|||||
|
[+4 29.10.08]
[+4 31.10.08] Регистрация: Jan 2008
Сообщений: 38
|
Цитата:
![]() Цитата:
Firexel Спасибо, но примерно из такой конструкции я его и достал. ![]() |
|
|||||
|
[+4 29.10.08]
[+4 31.10.08] Регистрация: Jan 2008
Сообщений: 38
|
Почитал про то как правильно писать на AS3.
Решил реализовать один пример кода по созданию кнопок программно и с надписями. В папке main разместил файлы RectangleButton.as и SimpleButtonDemo.as, во fla файле прописал класс документа "main.RectangleButton". Но при тестировании выводиться ошибки: Цитата:
При поиске что за ошибка 5000 и как с ней бороться нашёл на форуме советы: Цитата:
Вот интересно как сделать чтобы всё работало. ![]() RectangleButton.as package main {
import flash.display.*;
import flash.text.*;
// import flash.display.MovieClip;
import flash.filters.DropShadowFilter;
public class RectangleButton extends SimpleButton {
// The text to appear on the button
private var _text:String;
// Save the width and height of the rectangle
private var _width:Number;
private var _height:Number;
public function RectangleButton( text:String, width:Number, height:Number ) {
// Save the values to use them to create the button states
_text = text;
_width = width;
_height = height;
// Create the button states based on width, height, and text value
upState = createUpState();
overState = createOverState();
downState = createDownState();
hitTestState = upState;
}
// Create the display object for the button's up state
private function createUpState():Sprite {
var sprite:Sprite = new Sprite();
var background:Shape = createdColoredRectangle( 0x33FF66 );
var textField:TextField = createTextField( false );
sprite.addChild( background );
sprite.addChild( textField );
return sprite;
}
// Create the display object for the button's up state
private function createOverState():Sprite {
var sprite:Sprite = new Sprite();
var background:Shape = createdColoredRectangle( 0x70FF94 );
var textField:TextField = createTextField( false );
sprite.addChild( background );
sprite.addChild( textField );
return sprite;
}
// Create the display object for the button's down state
private function createDownState():Sprite {
var sprite:Sprite = new Sprite();
var background:Shape = createdColoredRectangle( 0xCCCCCC );
var textField:TextField = createTextField( true );
sprite.addChild( background );
sprite.addChild( textField );
return sprite;
}
// Create a rounded rectangle with a specific fill color
private function createdColoredRectangle( color:uint ):Shape {
var rect:Shape = new Shape();
rect.graphics.lineStyle( 1, 0x000000 );
rect.graphics.beginFill( color );
rect.graphics.drawRoundRect( 0, 0, _width, _height, 15 );
rect.graphics.endFill();
rect.filters = [ new DropShadowFilter( 2 ) ];
return rect;
}
// Create the text field to display the text of the button
private function createTextField( downState:Boolean ):TextField {
var textField:TextField = new TextField();
textField.text = _text;
textField.width = _width;
// Center the text horizontally
var format:TextFormat = new TextFormat();
format.align = TextFormatAlign.CENTER;
textField.setTextFormat( format );
// Center the text vertically
textField.y = ( _height - textField.textHeight ) / 2;
textField.y -= 2; // Subtract 2 pixels to adjust for offset
// The down state places the text down and to the right
// further than the other states
if ( downState ) {
textField.x += 1;
textField.y += 1;
}
return textField;
}
}
}
package main {
import flash.display.*;
public class SimpleButtonDemo extends Sprite {
public function SimpleButtonDemo() {
// Create three rectangular buttons with different text and
// different sizes, and place them at various locations within
// the movie
var button1:RectangleButton = new RectangleButton( "Button 1", 60, 100 );
button1.x = 20;
button1.y = 20;
var button2:RectangleButton = new RectangleButton( "Button 2", 80, 30 );
button2.x = 90;
button2.y = 20;
var button3:RectangleButton = new RectangleButton( "Button 3", 100, 40 );
button3.x = 100;
button3.y = 60;
// Add the buttons to the display list so they appear on-screen
addChild( button1 );
addChild( button2 );
addChild( button3 );
}
}
}
|
|
|||||
|
Регистрация: Jul 2008
Адрес: Рига
Сообщений: 176
|
Уважаемый, вы не знаете азов. Отложите эти 100 рецептов и прочтите нормальную книгу по as3. Очень советую, Essential ActionScript 3.0 | O'Reilly Media. Тогда вам всё станет ясно, и не будут возникать такие глупые вопросы.
Document class, являясь графическим объектом по натуре обязан напрямую наследоваться (если мне не изменяет память) либо от MovieClip, либо от Sprite, либо от Shape. То есть у вас должен быть третий класс, характеризующий Document class, который создаст вашу кнопку как-нибудь так: |
|
|||||
|
[+4 29.10.08]
[+4 31.10.08] Регистрация: Jan 2008
Сообщений: 38
|
Цитата:
Вобщем если его прописать во fla файле то ошибки 5000 не возникает, но по прежнему что то про метод addFrameScript пишут. Цитата:
![]() |
|
|||||
|
Регистрация: Jul 2008
Адрес: Рига
Сообщений: 176
|
Ещё раз:
Цитата:
|
|
|||||
|
[+4 29.10.08]
[+4 31.10.08] Регистрация: Jan 2008
Сообщений: 38
|
гм, а на других языках мне книжка не поможет.
|
![]() |
![]() |
Часовой пояс GMT +4, время: 01:13. |
|
|
« Предыдущая тема | Следующая тема » |
|
|