Reset mx:hslider value - flex4

I am new to flex and my question is how to reset mx hslider value with "reset" button.
here is a sample script:
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600">
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<fx:Script>
<![CDATA[
import mx.events.SliderEvent;
private var txtvalue:int = 0;
protected function Focal_changeHandler(event:SliderEvent):void
{
txtvalue = Focal.value;
if(txtvalue == 0)
Slider_txt.text = "Low";
if(txtvalue == 1)
Slider_txt.text = "Middle";
if(txtvalue == 2)
Slider_txt.text = "High";
}
]]>
</fx:Script>
<mx:HSlider id="Focal" x="476" y="345" maximum="2" minimum="0" value="0" buttonMode="true" enabled="true" snapInterval="1" tickInterval="1" allowTrackClick="true" liveDragging="true" change="Focal_changeHandler(event)"/>
<s:Label id="Slider_txt" x="472" y="319" text= "Low"/>
<s:Button x="476" y="459" label="Reset" id="Res_btn"/>
</s:Application>

Normally you could do
<s:Button x="476" y="459" label="Reset" id="Res_btn" click="{Focal.value = 0}"/>
But since you'd need to update the text as well, it's better to do an own method for that:
<s:Button x="476" y="459" label="Reset" id="Res_btn" click="onResetClick()"/>
and in your code part:
protected function Focal_changeHandler(event:SliderEvent):void
{
updateSliderText();
}
private function onResetClick():void
{
Focal.value = 0;
updateSliderText();
}
private function updateSliderText():void
{
txtvalue = Focal.value;
if (txtvalue == 0)
Slider_txt.text = "Low";
if (txtvalue == 1)
Slider_txt.text = "Middle";
if (txtvalue == 2)
Slider_txt.text = "High";
}

Related

Conversion of Visualforce page into LWC

Need help to convert my following VF page into LWC
VF code:
<apex:page showHeader="true" sidebar="true" controller="OrgWideOppBidContrl">
<apex:form >
<apex:pageBlock >
<apex:pageMessages id="pagMsg"/>
<apex:pageBlockSection >
<apex:pageBlockSectionItem >
<apex:outputText value="From" style="padding-top:5px;"/>
<apex:inputField value="{!opp.StartDate__c}" required="true"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
<apex:outputText value="To" style="padding-top:5px;"/>
<apex:inputField value="{!opp.EstimatedHarvestDate__c}" required="true"/>
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
<apex:commandButton value="start Batch " action="{!startBatchJob}" style="margin-left:500px;" reRender="pagMsg"/>
</apex:pageBlock>
</apex:form>
</apex:page>
Apex code:
public with sharing class OrgWideOppBidContrl {
public Opportunity opp{get;set;}
public OrgWideOppBidContrl(){
opp = new Opportunity();
opp.StartDate__c = Date.today();
opp.EstimatedHarvestDate__c = Date.today();
}
public PageReference startBatchJob(){
OrgWideOpportunityBidSetting__c orgwideOppBidSett = OrgWideOpportunityBidSetting__c.getInstance('OrgWideOppBid');
if(orgwideOppBidSett == null){
ApexPages.addMessage(new ApexPages.message(ApexPages.Severity.ERROR,'OrgWideOppBid not found'));
return null;
}
if(orgwideOppBidSett.InProgress__c == true){
ApexPages.addMessage(new ApexPages.message(ApexPages.Severity.WARNING,'Please wait Batch job for Org Wide Opportunity Bid is already in progress'));
return null;
}
String queryString = 'Select id From OrgWideMatch__c';
Database.executeBatch(new BatchExecutor(new DeleteOrgWideMatchData(), queryString, null), 1000);
ApexPages.addMessage(new ApexPages.message(ApexPages.Severity.INFO,'Batch job for Org Wide Opportunity Bid is started successfully'));
orgwideOppBidSett.InProgress__c = true;
orgwideOppBidSett.startDate__c = opp.StartDate__c;
orgwideOppBidSett.EndDate__c = opp.EstimatedHarvestDate__c;
update orgwideOppBidSett;
return null;
}
}

how to change IViewport verticalScrollPosition dynamicly

I'm trying to scroll VGroup with scroller:
<s:Scroller id="scroller" width="100" height="100">
<s:VGroup id="vp" width="100%" height="100%">
<my:TripView id="one"/>
<my:TripView id="two"/>
// if any more TripView.....
</s:VGroup>
</s:Scroller>
The TripView is dynamiclly generated, so the VGroup contentHeight may much greater than viewPortHeight. Since I could drag stuff in the TripView, I want to change the vp.verticalScrollPosition when the drag stuff almost move to the bottom of the view so the other TripView could be in the screen.
The most important thing is the scrollRect. Change the verticalScrollPosition based on the scrollRect. To use the ScrollManager, you should register viewport by registerViewport function. Then listen for mouseMove event, in the event listener invoke startScroll. Following is implementation:
package utils {
import flash.display.Stage;
import flash.events.MouseEvent;
import flash.geom.Point;
import flash.geom.Rectangle;
import mx.core.IInvalidating;
import spark.components.Group;
public class ScrollManager {
private var viewport:Group;
private var stage:Stage;
private var oldMovingMouseY:Number;
private static var _instance:ScrollManager;
//threshold for scrolling
private const FUDGE:Number = 35;
//scroll up speed
private const UP_SCROLL_DELTA:int = 50;
//scroll down speed
private const DOWN_SCROLL_DELTA:int = 80;
public function registerViewport(viewport:Group):void {
this.viewport = viewport;
this.stage = viewport.stage;
}
public static function getInstance():ScrollManager {
if(_instance == null) {
_instance = new ScrollManager();
}
return _instance;
}
public function startScroll(mouseEvent:MouseEvent):void {
oldMovingMouseY = mouseEvent.stageY;
stage.addEventListener(MouseEvent.MOUSE_MOVE, onMouseMove, false, 0, true);
stage.addEventListener(MouseEvent.MOUSE_UP, onMouseUp, false, 0, true);
}
private function onMouseUp(event:MouseEvent):void {
stage.removeEventListener(MouseEvent.MOUSE_MOVE, onMouseMove);
stage.removeEventListener(MouseEvent.MOUSE_UP, onMouseUp);
if (viewport is IInvalidating) {
//viewport.callLater(IInvalidating(viewport).validateNow);
//change VSP on scrollRect.y
var rect:Rectangle = viewport.scrollRect;
viewport.verticalScrollPosition = rect.y;
trace("========final vsp ========", rect.y);
}
}
private function onMouseMove(event:MouseEvent):void {
var currentMouseX:Number = event.stageX;
var currentMouseY:Number = event.stageY;
trace("mouseY ", currentMouseY);
//scroll direction
var delta:Number = currentMouseY - oldMovingMouseY;
var direction:int = (delta > 0) ? 1 : (delta < 0) ? -1: 0;
var scrollDelta:Number = direction > 0 ? DOWN_SCROLL_DELTA : UP_SCROLL_DELTA;
//current mousePoint in viewport coordination
var localPoint:Point = viewport.globalToLocal(new Point(currentMouseX, currentMouseY));
trace("localPoint: ", localPoint);
var scrollRect:Rectangle = viewport.scrollRect;
trace("viewport rect", scrollRect);
//determine if need scroll
if(needScroll(localPoint, scrollRect, direction)) {
trace("direction ", direction > 0 ? " UP": " DOWN");
scrollRect.y += scrollDelta*direction;
viewport.scrollRect = scrollRect;
if (viewport is IInvalidating) {
IInvalidating(viewport).validateNow();
}
}
oldMovingMouseY = currentMouseY;
}
private function needScroll(localPoint:Point, scrollRect:Rectangle, direction:int):Boolean {
var localY:Number = localPoint.y;
var bottom:Number = scrollRect.bottom;
var top:Number = scrollRect.top;
if(direction > 0 && (localY + FUDGE) > bottom) {
return true;
}
if(direction< 0 && (localY - FUDGE) < top) {
return true;
}
return false;
}
}
}

How to pass a value in a line chart in flex, from a database where I'm using java to pass the value

I am using trend lines from amcharts.
I am using java and passing the values from database uins blazeds [??].
I'm taking an array collection to fetch the values from the database and put it in trendlines.
So what's the error in the code and what should the correct code be?
<?xml version="1.0" encoding="utf-8"?>
<!-- This example is made using amStock Flex component. Visit http://flex.amcharts.com to see more examples -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
xmlns:amcharts="http://www.amcharts.com/com_internal"
backgroundColor="#FFFFFF"
width="100%" height="100%"
creationComplete="init()"
viewSourceURL="srcview/index.html">
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
<mx:Producer id="producer" destination="RandomDataPush1"
acknowledge="ack(event)" fault="handleFault(event)"/>
<mx:Consumer id="consumer" destination="RandomDataPush1"
message="messageHandler(event)" fault="handleFault(event)" />
</fx:Declarations>
<fx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
import com.amcharts.events.SerialChartEvent;
import mx.controls.Alert;
import mx.core.FlexGlobals;
import mx.messaging.events.MessageAckEvent;
import mx.messaging.events.MessageEvent;
import mx.messaging.events.MessageFaultEvent;
import mx.messaging.messages.AsyncMessage;
import mx.rpc.events.ResultEvent;
private var dataString:String =
[Bindable]
private var chartData:ArrayCollection = new ArrayCollection();
/* private function generateChartData():void
{
var firstDate:Date = new Date();
firstDate.setMinutes(firstDate.getMinutes() - 2000);
for(var i:Number = 0; i < 2000; i++)
{
var newDate:Z = new Date(firstDate);
newDate.setMinutes(newDate.getMinutes() + i);
var a:Number = Math.round(Math.random() * (40 + i)) + 100 + i;
var b:Number = Math.round(Math.random() * (1000 + i)) + 500 + i * 2;
chartData.addItem({date:newDate, a:a, b:b});
}
} */
private var Bindable:Object;
private function parseData():void{
// parse data string
var rowArray:Array = dataString.split("\n");
for(var i:uint = 0; i < rowArray.length; i++){
var row:Array = rowArray[i].split(",");
var dateArray:Array = row[0].split("-");
var date:Date = new Date(Number(dateArray[0]), Number(dateArray[1]) - 1, Number(dateArray[2]));
var open:Number = row[1];
var high:Number = row[2];
var low:Number = row[3];
var close:Number = row[4];
//chartData.addItem({date:date, open:open, high:high, low:low, close:close});
}
}
private function onClose():void
{
var msg:AsyncMessage = new AsyncMessage();
msg.body = "Close";
//msg.headers["symbol"]="IBKR";
msg.headers["symbol"]="EUR";
producer.send(msg);
consumer.subscribe();
//PopUpManager.removePopUp(this);
}
public function init():void {
// Alert.show("Hi from init..");
var msg:AsyncMessage = new AsyncMessage();
msg.body = "New";
//msg.headers["symbol"]="IBKR";
msg.headers["symbol"]="EUR";
producer.send(msg);
consumer.subscribe();
var ar:ArrayCollection=new ArrayCollection();
ar.addItemAt("EUR",0);
//pair_chart.dataProvider=ar;
//pair_chart.selectedIndex=0;
var ar1:ArrayCollection=new ArrayCollection();
ar1.addItemAt("Candle",0);
ar1.addItemAt("Bar",1);
}
private function ack(event:MessageAckEvent):void
{
//Alert.show(""+event.message.body);
chart.dataProvider = event.message.body as ArrayCollection;
//mybarChart.dataProvider = event.message.body as ArrayCollection;
}
private function handleFault(event:MessageFaultEvent):void
{
Alert.show("fault"+event.faultString);
}
private function messageHandler(event:MessageEvent):void
{
var dateTime:Date = new Date();
var obj:Object = new Object();
//Alert.show("hi "+event.message.body);
//obj.time = format.format(new Date()).toString();
//chart.dataProvider = event.message.body as ArrayCollection;
//FlexGlobals.topLevelApplication.crntpos.ui.chartArrCollection.addAll(event.message.body as ArrayCollection);
chartData.addAll(event.message.body as ArrayCollection);
//Alert.show("chartData.length "+chartData.length);
chart.dataProvider = chartData;
//Alert.show("hi "+chartData.list);
//mybarChart.dataProvider=FlexGlobals.topLevelApplication.crntpos.ui.chartArrCollection;
}
]]>
</fx:Script>
<s:VGroup width="100%" height="100%" paddingBottom="10" paddingTop="10" paddingLeft="10" paddingRight="10">
<amcharts:AmStockChart width="100%" height="100%">
<amcharts:dataSets>
<amcharts:DataSet id="chart" color="#00CC00" dataProvider="{chartData}" categoryField="date" title="First data set">
<amcharts:fieldMappings>
<amcharts:FieldMapping fromField="a" toField="value"/>
<amcharts:FieldMapping fromField="b" toField="volume"/>
</amcharts:fieldMappings>
</amcharts:DataSet>
</amcharts:dataSets>
<amcharts:panels>
<!-- to enabled drawing icons, you only need to set drawingIconsEnabled="true" on StockPanel -->
<amcharts:StockPanel drawingIconsEnabled="true" title="Value" height="50%" showCategoryAxis="true">
<amcharts:stockGraphs>
<amcharts:StockGraph bulletBorderColor="#FFFFFF" bullet="round" id="g1" valueField="value" compareField="value" comparable="true"/>
</amcharts:stockGraphs>
<amcharts:stockLegend>
<amcharts:StockLegend/>
</amcharts:stockLegend>
</amcharts:StockPanel>
</amcharts:panels>
<amcharts:periodSelector>
<amcharts:PeriodSelector position="bottom" width="157">
<amcharts:periods>
<amcharts:PeriodButton selected="true" label="1 Hour" period="hh" count="1"/>
<amcharts:PeriodButton label="2 Hours" period="hh" count="2"/>
<amcharts:PeriodButton label="6 Hours" period="hh" count="6"/>
<amcharts:PeriodButton label="1 Day" period="DD" count="1"/>
<amcharts:PeriodButton label="MAX" period="MAX"/>
</amcharts:periods>
</amcharts:PeriodSelector>
</amcharts:periodSelector>
<amcharts:chartScrollbarSettings>
<amcharts:ChartScrollbarSettings height="30" graph="{g1}"/>
</amcharts:chartScrollbarSettings>
<amcharts:categoryAxesSettings>
<amcharts:CategoryAxesSettings minPeriod="mm"/>
</amcharts:categoryAxesSettings>
<amcharts:chartCursorSettings>
<amcharts:ChartCursorSettings showValueAxisValue="true" crosshair="true"/>
</amcharts:chartCursorSettings>
</amcharts:AmStockChart>
</s:VGroup>
</s:Application>

AIR multiple HTTPService call Mac OSX

I am instantiating and sending multiple instances of HTTPService
On a Mac, however, many of the calls fail with a 2032 error.
<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
click="windowedapplication1_clickHandler(event)"
creationComplete="windowedapplication1_creationCompleteHandler(event)">
<fx:Script>
<![CDATA[
import mx.controls.Alert;
import mx.events.FlexEvent;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.rpc.http.HTTPService;
[Bindable]
private var r:int=0;
[Bindable]
private var f:int=0;
private var a:Array= ['url1', 'url2', 'url3', 'url4', 'url5'];
private var sa:Array=[];
protected function windowedapplication1_clickHandler(event:MouseEvent):void
{
for(var i:int=0; i<sa.length; i++) {
sa[i].send();
}
}
protected function windowedapplication1_creationCompleteHandler(event:FlexEvent):void
{
for(var i:int=0; i<100; i++) {
var random:int=Math.floor(Math.random() * a.length);
var s:HTTPService=new HTTPService();
s.addEventListener(ResultEvent.RESULT, sr);
s.addEventListener(FaultEvent.FAULT, sf);
s.resultFormat="text";
s.url=a[random];
sa.push(s);
}
//s.useProxy=true;
}
private function sf(e:FaultEvent):void {
f++;
t.text="MESSAGE: " + e.message + "HEADERS:" + e.headers + "FAULTCONTENT: " + e.fault.content
+ "ERROR: " + e.fault.errorID + "|" + e.fault.faultCode + "|" + e.fault.faultDetail + "|" + e.fault.faultString
+ "FAULTMESSAGE:" + e.fault.message + "FAULRNAME:" + e.fault.name + "ROOTCAUSE:" + e.fault.rootCause
+ "AT " + e.fault.getStackTrace();
}
private function sr(e:ResultEvent):void {
r++;
}
]]>
</fx:Script>
<fx:Declarations>
</fx:Declarations>
<s:Label x="10" y="19" text="Result {r}"/>
<s:Label x="10" y="120" text="Fault {f}"/>
<s:TextArea x="10" y="198" width="610" height="294" id="t"/>
</s:WindowedApplication>
It works as expected on PC (I get all 100 results as successful) but on a Mac, I get wuite a few that fail.
Why is this happening and how do I get around it?
It seems Win7 and Mac OS X block very quick requests to different addressed.
Adding a 1 second timeout works fine

Setting Spark DataGrid column's default sort on application's creationComplete (Flex 4.5)

I have a spark DataGrid component with several columns and I want to have my application default to descending order on the first column in the DataGrid. I would like to use the built-in default sort that occurs when clicking the top header once. I have no need to sort the ArrayCollection I'm working with or change what the comparators are.
I also want any user-generated sorting such as clicking on a different column's header to override the default sorting.
Does anyone have any ideas on how to go about this? Thanks.
Just use sortByColumn method:
var columnIndexes:Vector.<int> = Vector.<int>([ 0 ]);
dataGrid.sortByColumns(columnIndexes, true);
Here is a full example:
DataGridSort.mxml
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
creationComplete="sortDataGrid();">
<fx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
import mx.collections.ArrayList;
[Bindable]
private var dataProvider:ArrayCollection = new ArrayCollection(
[
new Product("iPad", "Detroit", 599),
new Product("iPod", "Burbank", 49),
new Product("iPod Nano", "Burbank", 39),
new Product("Flash Drive", "Burbank", 59),
new Product("iPod", "Burbank", 49),
new Product("Galaxy Tab", "Coldbridge", 499),
new Product("HTC Hero", "Abidjan", 700)
]);
private function sortDataGrid():void
{
// you can also use Vector.<int>([ 0, 1 ]); to sort by first 2 columns
var columnIndexes:Vector.<int> = Vector.<int>([ 0 ]);
// set 2nd argument to true to show sorting triangle
dataGrid.sortByColumns(columnIndexes, true);
}
]]>
</fx:Script>
<s:DataGrid id="dataGrid" horizontalCenter="0" verticalCenter="0" width="200"
dataProvider="{dataProvider}">
<s:columns>
<s:ArrayCollection>
<s:GridColumn dataField="name"/>
<s:GridColumn dataField="location"/>
<s:GridColumn dataField="price"/>
</s:ArrayCollection>
</s:columns>
</s:DataGrid>
</s:Application>
Product.as
package
{
import flash.events.EventDispatcher;
public class Product extends EventDispatcher
{
public function Product(name:String = null, location:String = null, price:Number = 0)
{
super();
this.name = name;
this.location = location;
this.price = price;
}
public var name:String;
public var location:String;
public var price:Number;
}
}
Alternatively if you don't want the datagrid to actually do the sort, for example when your dealing with a paging system with already sorted items. Extend the spark datagrid and add the following method:
public function PlaceSortIndicator(columnIndex:uint, descending:Boolean):void
{
if(columnIndex >= 0 && columns != null && columns.length > columnIndex)
{
var column:GridColumn = columns.getItemAt(columnIndex) as GridColumn;
if(column != null)
{
column.sortDescending = descending;
if (columnHeaderGroup)
columnHeaderGroup.visibleSortIndicatorIndices = new <int>[columnIndex];
}
}
}

Resources