Flex Modules and custom text field - apache-flex

This is a really strange one. I've created my own CustomTextField class which I am using to embed the font and set the defaultTextFormat. This is working absolutely fine, but for some reason when I try to create a new CustomTextField in any module but the parent application, text text is only showing sometimes.
Here is my CustomTextField class:
package uk.package.text
{
import flash.text.AntiAliasType;
import flash.text.Font;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.text.TextFormat;
public class CustomTextField extends TextField
{
[Embed(source='../assets/fonts/Arial.ttf',fontName='CustomFont',fontWeight='regular',
unicodeRange='U+0020-U+0040,U+0041-U+005A,U+005B-U+0060,U+0061-U+007A,U+007B-U+007E,U+0080-U+00FF,U+0100-U+017F,U+0400-U+04FF,U+0370-U+03FF,U+1E00-U+1EFF',
mimeType='application/x-font-truetype'
)]
public static var MY_FONT:Class;
[Embed(source='../assets/fonts/Arial Bold.ttf',fontName='CustomFont',fontWeight='bold',
unicodeRange='U+0020-U+0040,U+0041-U+005A,U+005B-U+0060,U+0061-U+007A,U+007B-U+007E,U+0080-U+00FF,U+0100-U+017F,U+0400-U+04FF,U+0370-U+03FF,U+1E00-U+1EFF',
mimeType='application/x-font-truetype'
)]
public static var MY_FONT_BOLD:Class;
public static const DEFAULT_FONT:String = "Arial";
public static const DEFAULT_TEXT_COLOUR:int = 0x000000;
public static const DEFAULT_TEXT_SIZE:int = 14;
private var _tf:TextFormat = new TextFormat(DEFAULT_FONT, DEFAULT_TEXT_SIZE, DEFAULT_TEXT_COLOUR);
public function CustomTextField():void
{
var CustomFont:Font = new MY_FONT();
_tf.font = CustomFont.fontName;
_tf.size = 16;
embedFonts = true;
antiAliasType = AntiAliasType.ADVANCED;
defaultTextFormat = _tf;
autoSize = TextFieldAutoSize.LEFT;
}
public override function set htmlText(value:String):void
{
super.htmlText = value;
setTextFormat(_tf);
}
public function get textFormat():TextFormat
{
return _tf;
}
}
}
It's weird how sometimes it works and sometimes it doesn't... perhaps there is something odd going on with the modules?

Ok, this one took me ages to figure out. I finally got it working by using the following code:
preinitialize="moduleLoader.moduleFactory=Application.application.systemManager;"
In the module loader item.
Thanks!

yes it's almost definitely a module issue. I've seen something similar before. I'm searching out the answer but my initial thought is to set
moduleLoader.applicationDomain = ApplicationDomain.currentDomain
Another issue is if you're loading the same module twice. If so you need to make the url unique by adding file.swf?<randomNumber> or something similar.

Related

Problem with adding Blocks to Minecraft Mod (1.15.2)

I have spent the last few hours adding a block to my Minecraft Mod. I have looked at several tutorials and none of them work. The blocks are not added to the Creative Inventory and I can't set them by command either. Unfortunately I didn't have any bugs in the console that I could show here. At some point I gave up and tried to do armor, here the same problem. On the other hand: normal items work (You can see the Item "ruby" which woked finde).
Here the code of my main class:
package de.thom.clashOfClasses;
import de.thom.clashOfClasses.init.ArmorMaterialList;
import de.thom.clashOfClasses.init.BlockList;
import de.thom.clashOfClasses.init.ItemList;
import net.minecraft.block.Block;
import net.minecraft.block.SoundType;
import net.minecraft.block.material.Material;
import net.minecraft.inventory.EquipmentSlotType;
import net.minecraft.item.ArmorItem;
import net.minecraft.item.BlockItem;
import net.minecraft.item.Item;
import net.minecraft.item.ItemGroup;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;
import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
#Mod("clashofclasses")
public class ClashOfClasses {
public static ClashOfClasses instance;
public static final String modid = "clashofclasses";
public static final Logger logger = LogManager.getLogger(modid);
public ClashOfClasses() {
instance = this;
FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup);
FMLJavaModLoadingContext.get().getModEventBus().addListener(this::clientRegistries);
MinecraftForge.EVENT_BUS.register(this);
}
public void setup(final FMLCommonSetupEvent event) {
logger.info("Setup method complete");
}
public void clientRegistries(final FMLClientSetupEvent event) {
logger.info("ClientRegistries method complete");
}
#Mod.EventBusSubscriber(bus = Mod.EventBusSubscriber.Bus.MOD)
public static class RegistryEvents {
#SubscribeEvent
public static void registerItems(final RegistryEvent.Register<Item> event) {
logger.info("Item Registry started");
event.getRegistry().registerAll(
ItemList.RUBY,
ItemList.ruby_block = new BlockItem(BlockList.ruby_block,new Item.Properties().group(ItemGroup.MISC)).setRegistryName(BlockList.ruby_block.getRegistryName())
);
logger.info("Items registerd");
}
#SubscribeEvent
public static void registerBlocks(final RegistryEvent.Register<Block> event) {
logger.info("Block Registry started");
event.getRegistry().registerAll
(
BlockList.ruby_block = new Block(Block.Properties.create(Material.IRON).hardnessAndResistance(2.0f,3.0f).lightValue(5).sound(SoundType.METAL)).setRegistryName(location("ruby_block"))
);
logger.info("Blocks registerd");
}
private static ResourceLocation location(String name){
return new ResourceLocation(ClashOfClasses.modid, name);
}
}
}
Here is the code of BlockList
package de.thom.clashOfClasses.init;
import net.minecraft.block.Block;
public class BlockList {
public static Block ruby_block;
}
Here is the code of ItemList:
package de.thom.clashOfClasses.init;
import de.thom.clashOfClasses.ClashOfClasses;
import net.minecraft.inventory.EquipmentSlotType;
import net.minecraft.item.ArmorItem;
import net.minecraft.item.Item;
import net.minecraft.item.ItemGroup;
import net.minecraft.util.ResourceLocation;
public class ItemList
{
//Test Items
public static Item RUBY = new Item(new Item.Properties().group(ItemGroup.MATERIALS)).setRegistryName(location("ruby"));
public static Item ruby_block;
private static ResourceLocation location(String name){
return new ResourceLocation(ClashOfClasses.modid, name);
}
}
A block in the world and a “block” in an inventory are very different things. A block in the world is represented by an IBlockState, and its behavior defined by an instance of Block. Meanwhile, an item in an inventory is an ItemStack, controlled by an Item. As a bridge between the different worlds of Block and Item, there exists the class ItemBlock. ItemBlock is a subclass of Item that has a field block that holds a reference to the Block it represents. ItemBlock defines some of the behavior of a “block” as an item, like how a right click places the block. It’s possible to have a Block without an ItemBlock. (E.g. minecraft:water exists a block, but not an item. It is therefore impossible to hold it in an inventory as one.)
When a block is registered, only a block is registered. The block does not automatically have an ItemBlock. To create a basic ItemBlock for a block, one should use new ItemBlock(block).setRegistryName(block.getRegistryName()). The unlocalized name is the same as the block’s. Custom subclasses of ItemBlock may be used as well. Once an ItemBlock has been registered for a block, Item.getItemFromBlock can be used to retrieve it. Item.getItemFromBlock will return null if there is no ItemBlock for the Block, so if you are not certain that there is an ItemBlock for the Block you are using, check for null.
from https://mcforge.readthedocs.io/en/latest/blocks/blocks/.
I short, if everything works, your blocks shoudnt appear in your
#ObjectHolder(modid)
#Mod.EventBusSunscriber(modid = modid, bus = Bus.Mod)
public class BlockInit {
public static final Block example_block = null;
#SubscribeEvent
public static void registerBlocks(final RegistryEvent.Register<Block> event) {
event.getRegistry().register(new Block(Block.Properties.create(Material)).setRegistry("example_block"));
}
#SubscribeEvent
public static void registerBlockItems(final RegistryEvent.Register<Item> event){
event.getRegistry().register(new BlockItem(example_item, new Item.Properties().group(ItemGroup)).setRegistry("example_block"));
}
That works for me just replace example_block with the name of your block and add more properties if you want
for another block just repeat the event.getRegistry stuff and use the name of your new block instead of example_block.
and don't forget to do the json files

JavaFX ChoiceBox add separator with type safety

I'm looking to add a separator into a choice box and still retain the type safety.
On all of the examples I've seen, they just do the following:
ChoiceBox<Object> cb = new ChoiceBox<>();
cb.getItems().addAll("one", "two", new Separator(), "fadfadfasd", "afdafdsfas");
Has anyone come up with a solution to be able to add separators and still retain type safety?
I would expect that if I wanted to add separators, I should be able do something along the following:
ChoiceBox<T> cb = new ChoiceBox<T>();
cb.getSeparators().add(1, new Separator()); // 1 is the index of where the separator should be
I shouldn't have to sacrifice type safety just to add separators.
As already noted, are Separators only supported if added to the items (dirty, dirty). To support them along the lines expected in the question, we need to:
add the notion of list of separator to choiceBox
make its skin aware of that list
While the former is not a big deal, the latter requires a complete re-write (mostly c&p) of its skin, as everything is tightly hidden in privacy. If the re-write has happened anyway, then it's just a couple of lines more :-)
Just for fun, I'm experimenting with ChoiceBoxX that solves some nasty bugs in its selection handling, so couldn't resist to try.
First, add support to the ChoiceBoxx itself:
/**
* Adds a separator index to the list. The separator is inserted
* after the item with the same index. Client code
* must keep this list in sync with the data.
*
* #param separator
*/
public final void addSeparator(int separator) {
if (separatorsList.getValue() == null) {
separatorsList.setValue(FXCollections.observableArrayList());
}
separatorsList.getValue().add(separator);
};
Then some changes in ChoiceBoxXSkin
must listen to the separatorsList
must expect index-of-menuItem != index-of-choiceItem
menuItem must keep its index-of-choiceItem
At its simplest, the listener re-builds the popup, the menuItem stores the dataIndex in its properties and all code that needs to access a popup by its dataIndex is delegated to a method that loops through the menuItems until it finds one that fits:
protected RadioMenuItem getMenuItemFor(int dataIndex) {
if (dataIndex < 0) return null;
int loopIndex = dataIndex;
while (loopIndex < popup.getItems().size()) {
MenuItem item = popup.getItems().get(loopIndex);
ObservableMap<Object, Object> properties = item.getProperties();
Object object = properties.get("data-index");
if ((object instanceof Integer) && dataIndex == (Integer) object) {
return item instanceof RadioMenuItem ? (RadioMenuItem)item : null;
}
loopIndex++;
}
return null;
}
Well you can work around it by creating an interface and then subclassing Separator to implement this interface:
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.beans.property.ReadOnlyObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.Separator;
import javafx.scene.layout.GridPane;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class ChoiceBoxIsSafe extends Application {
interface FruitInterface { }
static public class Fruit implements FruitInterface {
private StringProperty name = new SimpleStringProperty();
Fruit(String name) {
this.name.set(name);
}
public StringProperty nameProperty() {
return name;
}
#Override
public String toString() {
return name.get();
}
}
static public class FruitySeparator extends Separator implements FruitInterface { }
#Override
public void start(Stage primaryStage) throws Exception {
GridPane grid = new GridPane();
grid.setHgap(10); grid.setVgap(10); grid.setPadding(new Insets(10));
ChoiceBox<FruitInterface> cb = new ChoiceBox<>();
cb.getItems().addAll(new Fruit("Apple"), new Fruit("Orange"), new FruitySeparator(), new Fruit("Peach"));
Text text = new Text("");
ReadOnlyObjectProperty<FruitInterface> selected = cb.getSelectionModel().selectedItemProperty();
text.textProperty().bind(Bindings.select(selected, "name"));
grid.add(cb, 0, 0);
grid.add(text, 1, 0);
Scene scene = new Scene(grid);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
but that is hardly an "elegant" solution and cannot be done in all cases (e.g. ChoiceBox<String>).
From the implementation of ChoiceBox it certainly looks like it wasn't a good idea to treat Separators like items in the ChoiceBox :-(.
FOR THE REST OF US:
There is a MUCH easier way to do this using code (there are easy ways to do it using FXML too, doing it in code offers more flexibility).
You simply create an ObservableList, then populate it with your items, including the separator then assign that list to the ChoiceBox like this:
private void fillChoiceBox(ChoiceBox choiceBox) {
ObservableList items = FXCollections.observableArrayList();
items.add("one");
items.add("two");
items.add("three");
items.add(new Separator());
items.add("Apples");
items.add("Oranges");
items.add("Pears");
choiceBox.getItems().clear();
choiceBox.getItems().addAll(items);
}

creating submenu's in flex context menu

Is there any workaround to create submenu in a flex context menu other than stopping right click from javascript.
Regards,
Hi Frank,
Yes, I want to create submenus in a context menu. Can you help me here.
Regards,
Hi Frank,
I need the context menu for the application not for datagrid.
In my initial question the phrase "other than stopping right click from javascript" means
"catch the right click in html, call a javascript function and over js call a as function."
The project that you have specified does the above procedure. I don't want to use this
procedure. Is there any other way for achieving submenus in a flex context menu. Could you
please tell me if so..
Regards,
Arvind
Yes, there is.
I don't know, what you exactly mean with this:
other than stopping right click from
javascript.
But, if you want to create a entry in submenu, do this:
//Instance of my own class
private var myContext:myContextMenu = new myContextMenu();
application.contextMenu = myContext.myContextMenu;
//Here is the Class:
package com.my.components
{
/* ////////////////////////////////////////////
///// My Context Menü /////////////////////
///////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
//to use: //
// private var myContext:MyContextMenu = new MyContextMenu(); //
// init() in creationComplete //
// application.contextMenu = myContext.myContextMenu; //
////////////////////////////////////////////////////////////////////////////// */
import flash.display.Sprite;
import flash.events.ContextMenuEvent;
import flash.net.URLRequest;
import flash.net.navigateToURL;
import flash.text.TextField;
import flash.ui.ContextMenu;
import flash.ui.ContextMenuBuiltInItems;
import flash.ui.ContextMenuItem;
public class MyContextMenu extends Sprite
{
public var myContextMenu:ContextMenu;
private var menuLabel:String = String.fromCharCode(169)+" My Company GmbH";
public function MyContextMenu()
{
myContextMenu = new ContextMenu;
removeDefaultItems();
addCustomItems();
myContextMenu.addEventListener(ContextMenuEvent.MENU_SELECT, menuSelectHandler);
super();
}
private function removeDefaultItems():void
{
myContextMenu.hideBuiltInItems();
var defaultItems:ContextMenuBuiltInItems = myContextMenu.builtInItems;
defaultItems.print = true;
}
private function addCustomItems():void
{
var item:ContextMenuItem = new ContextMenuItem(menuLabel);
myContextMenu.customItems.push(item);
item.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT,menuItemSelectHandler);
}
private function menuSelectHandler(event:ContextMenuEvent):void
{
}
private function menuItemSelectHandler(event:ContextMenuEvent):void
{
navigateToURL(new URLRequest('http://www.my-company.de'));
}
private function createLabel():TextField
{
var txtField:TextField = new TextField();
//txtField.text = textLabel;
txtField.text = "RightClickHere";
return txtField;
}
}
}
Have fun
EDIT:
There is an interesting project here. They catch the right click in html, call a javascript function and over js call a as function.
Unfortunately, the limitation of FP or NativeMenu APi allowed just on level contextmenu. Read here
Frank

AS3: AddChild issue -- "TypeError: Error #2007: Parameter child must be non-null."

My following code gave me
TypeError: Error #2007: Parameter child must be non-null runtime error.
not sure why...I would appreciate any help...
mySb = new ScrollBar();
mySb.x = cont.x; //+ cont.width;
mySb.y = cont.y;
mySb.height = contMask.height;
mySb.enabled = true;
addChild(mySb);
Updated
package com.search.view
{
import com.search.events.YouTubeSearchEvent;
import fl.controls.ScrollBar;
import fl.controls.Slider;
import fl.controls.UIScrollBar;
import fl.events.ScrollEvent;
import fl.events.SliderEvent;
import flash.display.Shape;
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.geom.Rectangle;
import flash.net.URLLoader;
public class SearchResultContainer extends Sprite
{
private var cont:videoCont;
private var contMask:Sprite;
private var mySb:ScrollBar;
public function SearchResultContainer()
{
super();
}
public function get selectedVideoID():String{
return newVideoID;
}
public function createContainer(_x:Number,_y:Number, videoResult:Array):void{
cont=new videoCont();
cont.x=_x;
cont.y=_y;
addChild(cont);
contMask = new Sprite();
contMask.x = cont.x;
contMask.y = cont.y;
createMask(contMask,0x000000,452,88);
addChild(contMask);
cont.mask = contMask;
mySb = new ScrollBar();
mySb.x = cont.x; //+ cont.width;
mySb.y = cont.y;
mySb.height = contMask.height;
mySb.enabled = true;
addChild(mySb); //problem code here...
}
private function createMask(inSrc:*,inColor:Number=0x999999,inW:Number=80,inH:Number=50):void{
var rect:Shape=new Shape();
rect.graphics.clear();
rect.graphics.beginFill(inColor);
rect.graphics.drawRect(0,0,inW,inH);
rect.graphics.endFill();
inSrc.addChild(rect);
}
}
}
I am in Flex environment....
Try to add a breakpoint before the problem occurs and check the mySb value , it looks like it's probably null , if it's not you'll have to look for null values either in the DisplayObjects you're using or the properties you're assigning them... if it is null , maybe you need to set more properties to your ScrollBar instance before adding it to the display list...
In my case I solved it adding the component to the movie library, but working in Flash CS5.5 environment.

Flex switch item-renderer

I was wondering if anyone had any luck with the following senario in flex.
I'd like to be able to have a custom item renderer which delegates to another renderer inside.
The reason for this would be in a datagrid for instance displaying a checkbox if the dataprovider for the row had a boolean value. Using the default item renderer when the value was a non boolean.
Basically I was hoping to use a proxy object (though not necessarily the proxy class) so that I could a renderer which delegated all of its responsibilties to a sub renderer.
Hard to explain.
Edit 1
I think the following gives a clearer idea of what I had in mind. This is only knocked up quickly for the purpose of showing the idea.
SwitchingRenderer.as
package com.example
{
import mx.controls.CheckBox;
import mx.controls.dataGridClasses.DataGridItemRenderer;
import mx.controls.listClasses.BaseListData;
import mx.controls.listClasses.IDropInListItemRenderer;
import mx.core.IDataRenderer;
import mx.core.UIComponent;
public class SwitchingRenderer extends UIComponent implements IDataRenderer, IDropInListItemRenderer
{
private var checkboxRenderer:CheckBox;
private var defaultRenderer:DataGridItemRenderer;
private var currentRenderer:IDataRenderer;
public function SwitchingRenderer()
{
this.checkboxRenderer = new CheckBox();
this.defaultRenderer = new DataGridItemRenderer();
this.currentRenderer = defaultRenderer();
super();
}
public function get data():Object
{
//If the data for this cell is a boolean
// currentRender = checkBoxRenderer
// otherwise
// currentRenderer = defaultRenderer
}
public function set data(value:Object):void
{
currentRenderer.data = value;
}
public function get listData():BaseListData
{
return currentRenderer.listData;
}
public function set listData(value:BaseListData):void
{
currentRenderer.listData = value;
}
}
}
If you're using Flex 4 spark components look into the itemRendererFunction,
Here is a good sample from the interwebs.
Unfortunately, Flex 3 components, such as the DataGrid do not support that.
You're a bit vague on what you'd be displaying if the data sent into the itemRenderer was not a Boolean value. But, you can easily modify the visual appearance of a component based on the data change event, including swapping visible properties of a component's children, changing states or change the selectedIndex of a ViewStack. All these things can be done within an itemRenderer w/o issues.
Edit:
Based on the user's additional posting, I'd add that what he is after can be done like this:
public function get data():Object
{
if(this.data is Boolean){
checkBoxRenderer.visible = true;
defaultRenderer.visible = false;
} else {
checkBoxRenderer.visible = false;
defaultRenderer.visible = true;
}
}

Resources