AS3 Using a variable with Transform - transform

I have a text field and a background and want to apply color using
myColorPicker. Either the text field or background can be selected using
radioGroup1. When either radio button is selected the trace statement
traces the variable obj2Clr exactly. However when I use that variable
with Transform, I can't apply color. If I hard code and use the actual
object then it works.
Can I not use a variable with Transform or is something else missing?
My code is below:
var radioGroup1:RadioButtonGroup = new RadioButtonGroup("selObj");
bkg_rb.label = "Background";
text_rb.label = "Text";
bkg_rb.group = radioGroup1;
text_rb.group = radioGroup1;
var obj2Clr;//which object to apply color to
radioGroup1.addEventListener(MouseEvent.CLICK, getObj);
function getObj(e:MouseEvent):void {
if (bkg_rb.selected == true) {
obj2Clr = "MovieClip(parent).design_mc.bkg_mc";
trace(obj2Clr);
} else if (text_rb.selected == true) {
obj2Clr = "MovieClip(parent).design_mc.info_txt";
trace(obj2Clr);
}
}
var colorTrans:ColorTransform = new ColorTransform();
var trans:Transform = new Transform(obj2Clr);
//var trans:Transform = new Transform(MovieClip(parent).design_mc.info_txt);
myColorPicker.addEventListener(ColorPickerEvent.CHANGE, changeColor);
function changeColor(event:ColorPickerEvent):void {
var myColor = "0x" + event.target.hexValue;
colorTrans.color = myColor;
trans.colorTransform = colorTrans;
trace("color selected is " + myColor);
}
Thanks for your help in advance:)
Debbie D

According to this code, obj2Clr is being initialized with a string literal?
For example, shouldn't this snippet:
if (bkg_rb.selected == true) {
obj2Clr = "MovieClip(parent).design_mc.bkg_mc";
trace(obj2Clr);
}
be:
if (bkg_rb.selected == true) {
obj2Clr = MovieClip(parent).design_mc.bkg_mc;
trace(obj2Clr);
}
?

Thanks, yes I thought I had to use a string literal with Transform because tracing out the variable without quotes that make it a literal resulted in [object MovieClip] and [object TextField].
So I removed the quotes and Transform still is not receiving the new Transform object. Yet when I hard code (which was commented out in the above example) everything is fine. Any other area I should check?
Debbie D :)

Related

Scanner Mismatch Exception when reading text file

My scanner is reading from a text file with the use of a delimiter. However when I run the program the only line that gets printed out is the first line of data then I get thrown an input mismatch exception. I believe the error is that it doesn't move onto the next line. I understand how the mismatch works I am just unsure how to fix it. I have tried putting scanner.nextLine(); in as you can see in my code below.
Here is my code for the scanner :
/**
* Method for reading the data from the electricToolData.txt file.
*/
public void readElectricToolData()
{
Frame myFrame = null; // initialises frame to null
FileDialog fileBox = new FileDialog(myFrame,
"Open", FileDialog.LOAD);
fileBox.setVisible(true);
String directoryPath = fileBox.getDirectory();
String filename = fileBox.getFile();
System.out.println(filename + " " + directoryPath); // prints out name of file and directory path
try {
File dataFile = new File(filename);
Scanner scanner = new Scanner(dataFile);
while(scanner.hasNext())
{
String lineOfText = scanner.nextLine(); // reads the next line of the file and stores as String
//if statement checks if line starts with either "//" or space.
if (lineOfText.startsWith("//") || lineOfText.isEmpty())
{
}
else // now got real data
{
Scanner scanner2 = new Scanner(lineOfText);
scanner2.useDelimiter(",");
lineOfText.trim();
System.out.println(lineOfText);
while(scanner2.hasNext())
{
//lineOfText.trim();
boolean mRechargeable = scanner.nextBoolean();
String mPower = scanner.next();
String mToolName = scanner.next();
String mItemCode = scanner.next();
int mTimesBorrowed = scanner.nextInt();
boolean mOnLoan = scanner.nextBoolean();
int mCost = scanner.nextInt();
int mWeight = scanner.nextInt();
scanner.nextLine();
ElectricTool electricTool = new ElectricTool(mToolName, mItemCode, mTimesBorrowed, mCost, mWeight, mPower);
toolsList.add(electricTool);
}
}
//System.out.println(lineOfText); // prints out string
}
scanner.close();
scanner.close(); // closes scanner
}
catch(FileNotFoundException e)
{
System.err.println("Caught IOException: " + e.getMessage());
}
}
The error gets shown at the boolean mRechargeable = scanner.nextBoolean();.
Here is the data file :
// this is a comment, any lines that start with //
// (and blank lines) should be ignored
// data is rechargeable, power, toolName, itemCode, timesBorrowed, onLoan, cost, weight
true,18V,Makita BHP452RFWX,RD2001,12,false,14995,1800
true,10.8V,Flex Impact Screwdriver FIS439,RD2834,14,true,13499,1200
false,1350W,DeWalt D23650-GB Circular Saw, RD6582,54,true,14997,5400
false,1500W,Milwaukee DD2-160XE Diamond Core Drill,RD4734,50,false,38894,9000
true,10.8V,Bosch GSR10.8-Li Drill Driver,RD3021,25,true,9995,820
false,900W,Bosch GSB19-2REA Percussion Drill,RD8654,85,false,19999,4567
true,10.8V,Flex Impact Screwdriver FIS439, RD2835,14,false,13499,1200
true,18V,DeWalt DW936 Circular Saw,RD4352,18,false,19999,3300
false,2100W,Sparky FK652 Wall Chaser,RD7625,15,false,29994,8400
The problem is that String.trim() doesn't work the way you think it does: it doesn't mutate the String it is called on, but returns a new String that effectively has the whitespace removed. This is causing the line to not be trimmed, and that "blank line" that has a lot of space characters on it then fails to be parsed with your first scanner.nextBoolean() call.
So, update:
String lineOfText = scanner.nextLine(); // reads the next line of the file and stores as String
to be:
// read the next line of the file, removing enclosing whitespace
String lineOfText = scanner.nextLine().trim();
Comments should ideally preceed the line, as it is easier to read and format, and more obvious that it is a comment. Also remove the redundant lineofText.trim(); later in the code.
Further, remember to close all Scanner instances when finished (so here one for each line, and one for the file).
The next problem is that in the inner loop, where you construct your ElectricTool instances, you are calling methods on scanner, rather than scanner2 (rename this to something more semantic, eg itemScanner):
Scanner itemScanner = new Scanner(lineOfText);
itemScanner.useDelimiter(",");
boolean mRechargeable = itemScanner.nextBoolean();
String mPower = itemScanner.next();
String mToolName = itemScanner.next();
String mItemCode = itemScanner.next();
int mTimesBorrowed = itemScanner.nextInt();
boolean mOnLoan = itemScanner.nextBoolean();
int mCost = itemScanner.nextInt();
int mWeight = itemScanner.nextInt();

AS3 call function upon clicking a line from a textfield

How do you call a different function when a line of text from a TextField/TextArea is clicked?
I already have a function which retrieves a description when any point of the TextField is clicked:
list.text = "chicken";
list.addEventListener(MouseEvent.CLICK, getter);
var descriptionArray:Array = new Array();
descriptionArray[0] = ["potato","chicken","lemon"];//words
descriptionArray[1] = ["Round and Brown","Used to be alive","Yellow"];//descriptions
function getter(e:MouseEvent):void
{
for (var i:int = 0; i < descriptionArray.length; i++)
{
var str:String = e.target.text;//The text from the list textfield
if (str == descriptionArray[0][i]) //if the text from List is in the array
{
trace("found it at index: " + i);
description.text = descriptionArray[1][i];//displays "Used to be alive".
}
else
{
trace(str+" != "+descriptionArray[0][i]);
}
}
}
It works fine, and returns the correct description.
But I want it to instead retrieve a different description depending on what line in the TextField/TextArea was clicked, like, if I used list.text = "chicken\npotato"
I know I can use multiple textfields to contain each word, but the list might contain over 100 words, and I want to use the TextArea's scrollbar to scroll through the words in the list, and if I used multiple textfields/areas, each one would have its own scrollbar, which is pretty pointless.
So, how do I call a different function depending on what line I clicked?
PS: It's not technically a different function, it's detecting the string in the line that was clicked, I just put it that way for minimal confusion.
There are a few built-in methods that should make your life easier:
function getter(e:MouseEvent):void
{
// find the line index at the clicked point
var lineIndex:int = list.getLineIndexAtPoint(e.localX, e.localY);
// get the text at that line index
var itemText:String = list.getLineText(lineIndex).split("\n").join("").split("\r").join("");
// find the text in the first array (using indexOf instead of looping)
var itemIndex:int = descriptionArray[0].indexOf(itemText);
// if the item was found, you can use the sam index to
// look up the description in the second array
if(itemIndex != -1)
{
description.text = descriptionArray[1][itemIndex];
}
}

Delete Selected Text from Textbox and Enter New Char in C#.NET

I am trying to delete selected text from textbox and enter new character in place of it.
For example, if textbox consists of 123456 and I select 345, and press r on the keyboard, it should replace the selected text.
here is my code:
string _selectText = txtCal.SelectedText;
string _text = Convert.ToString(btn.Text);
if (_selectText.Length > 0) {
int SelectionLenght = txtCal.SelectionLength;
string SelectText = txtCal.Text.Substring(txtCal.SelectionStart, SelectionLenght);
txtCal.Text = ReplaceMethod(SelectText, _text);
}
//replace method function
public string ReplaceMethod(string replaceString, string replaceText) {
string newText = txtCal.Text.Replace(replaceString, replaceText);
return newText;
}
Can anyone show me where my mistake is?
The replace-based answer offered above may well replace the wrong instance of the selection, as noted in the comments. The following works off positions instead, and doesn't suffer that problem:
textbox1.Text = textbox1.Text.Substring(0, textbox1.SelectionStart) + textbox1.Text.Substring(textbox1.SelectionStart + textbox1.SelectionLength, textbox1.Text.Length - (textbox1.SelectionStart + textbox1.SelectedText.Length));
The following does what you want and then selects the replacing text :)
string _text = Convert.ToString(btn.Text);
int iSelectionStart = txtCal.SelectionStart;
string sBefore = txtCal.Text.Substring(0, iSelectionStart);
string sAfter = txtCal.Text.Substring(iSelectionStart + txtCal.SelectionLength);
txtCal.Text = sBefore + _text + sAfter;
txtCal.SelectionStart = iSelectionStart;
txtCal.SelectionLength = _text.Length;
Try this instead
if (textbox1.SelectedText.Length > 0)
{
textbox1.Text = textbox1.Text.Replace(text1.Text.Substring(textbox1.SelectionStart, textbox1.SelectionLength), btn.Text);
}
This is essentially the same as other answers, but formatted differently using C# 6.0.
// If there is selected text, it will be removed before inserting new text.
// If there is no selected text, the new text is inserted at the caret index.
string before = textBox.Text.Substring(0, textBox.SelectionStart);
string after = textBox.Text.Substring(textBox.SelectionStart + textBox.SelectedText.Length);
textBox.Text = $"{before}{insertText}{after}";
textBox.CaretIndex = $"{before}{insertText}".Length;
Note that I set the CaretIndex to a new position after changing the text. This may be useful since the caret index resets to zero when changing the text like this. You may also want to focus the textbox to draw the user's attention to the change and allow them to know where the caret currently is.

Insert image into a specified location

I have a Google Apps script which replaces placeholders in a copy of a template document with some text by calling body.replaceText('TextA', 'TextB');.
Now I want to extend it to contain images. Does anybody have idea how to do this?
Thank you,
Andrey
EDIT: Just to make it clear what my script does. I have a Google form created in a spreadsheet. I've created a script which runs upon form submission, traverses a sheet corresponding to the form, find unprocessed rows, takes values from corresponding cells and put them into a copy of a Google document.
Some fields in the Google form are multi-line text fields, that's where '\r\r' comes from.
Here's a workaround I've come up with by now, not elegant, but it works so far:
// replace <IMG src="URL"> with the image fetched from URL
function processIMG_(Doc) {
var totalElements = Doc.getNumChildren();
for( var j = 0; j < totalElements; ++j ) {
var element = Doc.getChild(j);
var type = element.getType();
if (type =='PARAGRAPH'){
var par_text = element.getText();
var start = par_text.search(new RegExp('<IMG'));
var end = par_text.search(new RegExp('>'));
if (start==-1)
continue;
// Retrieve an image from the web.
var url = getURL_(par_text.substring(start,end));
if(url==null)
continue;
// Before image
var substr = par_text.substring(0,start);
var new_par = Doc.insertParagraph(++j, substr);
// Insert image
var resp = UrlFetchApp.fetch(url);
new_par.appendInlineImage(resp.getBlob());
// After image
var substr = par_text.substring(end+1);
Doc.insertParagraph(++j, substr);
element.removeFromParent();
j -= 2; // one - for latter increment; another one - for increment in for-loop
totalElements = Doc.getNumChildren();
}
}
}
Here is a piece of code that does (roughly) what you want.
(there are probably other ways to do that and it surely needs some enhancements but the general idea is there)
I have chosen to use '###" in the doc to mark the place where the image will be inserted, the image must be in your google drive (or more accurately in 'some' google drive ).
The code below uses a document I shared and an image I shared too so you can try it.
here is the link to the doc, don't forget to remove the image and to put a ### somewhere before testing (if ever someone has run the code before you ;-)
function analyze() { // just a name, I used it to analyse docs
var Doc = DocumentApp.openById('1INkRIviwdjMC-PVT9io5LpiiLW8VwwIfgbq2E4xvKEo');
var image = DocsList.getFileById('0B3qSFd3iikE3cF8tSTI4bWxFMGM')
var totalElements = Doc.getNumChildren();
var el=[]
for( var j = 0; j < totalElements; ++j ) {
var element = Doc.getChild(j);
var type = element.getType();
Logger.log(j+" : "+type);// to see doc's content
if (type =='PARAGRAPH'){
el[j]=element.getText()
if(el[j]=='###'){element.removeFromParent();// remove the ###
Doc.insertImage(j, image);// 'image' is the image file as blob
}
}
}
}
EDIT : for this script to work the ### string MUST be alone in its paragraph, no other character before nor after... remember that each time one forces a new line with ENTER the Document creates a new paragraph.

Why does calling the YUI Datatable showCellEditor not display the editor?

Clicking on the second cell (any row) in the datatable causes the cell editor to display. But, I am trying to display the cell editor from code. The code looks like the following:
var firstEl = oDataTable.getFirstTdEl(rowIndex);
var secondCell = oDataTable.getNextTdEl(firstEl);
oDataTable.showCellEditor(secondCell);
When I debug into the datatable.js code (either with a click or from the code above) it follows the same path through the showCellEditor function but the above code will not display the editor.
I am using YUI version 2.8.0r4.
I think this is blur events issue.
So, for example, I have link that must add record to datatable, and show its editor.
var mymethod = function (e) {
YAHOO.util.Event.stopEvent(e);
var r = {};
r.id = 0;
r.value = 'hello world';
myDataTable.addRow(r);
var cell = myDataTable.getLastTrEl().cells[0];
myDataTable.showCellEditor(cell);
}
YAHOO.util.Event.addListener('mylink2addrecord_ID', 'click', mymethod);
Without stopEvent you will never see editor, because there is tableBlur event called when you click on yourlink....
You can try this - this is ONLY a snippet from a larger piece of an event handler set of code I have. EditNext is the function that moves over a cell and displays the editor, if the cell has one:
this.myDataTable.subscribe("editorKeydownEvent",function(oArgs) {
var self = this,
ed = this._oCellEditor, // Should be: oArgs.editor, see: http://yuilibrary.com/projects/yui2/ticket/2513909
ev = oArgs.event,
KEY = YAHOO.util.KeyListener.KEY,
Textbox = YAHOO.widget.TextboxCellEditor,
Textarea = YAHOO.widget.TextareaCellEditor,
DCE = YAHOO.widget.DateCellEditor,
cell = ed.getTdEl(),
col = ed.getColumn(),
row,rec,
editNext = function(cell) {
cell = self.getNextTdEl(cell);
while (cell && !self.getColumn(cell).editor) {
cell = self.getNextTdEl(cell);
}
if (cell) {
self.showCellEditor(cell);
}
},
As mac said, you need to stop the previous event. For some reason it (the tableBlur event) conflicts with the showCellEditor function. This is the first place which had a resolution to the problem.
To sum it up, all I did was:
YAHOO.util.Event.stopEvent(window.event);<br/>
dt.showCellEditor(td); // dt = yui datatable obj, td = {record: yuirecord, column: yuicolumn}
Of course if you have the event object readily available as mac's post does, you can pass it to stopEvent(e) like he did.

Resources