How to add zoom to this code? On touch works great and moves image - android-studio

Is there anyway to use matrix or scale gesture to this code ? I can move image arround x,y but cant zoom in or out. Any advice would be welcome :)
this is my class
class SimpleFloatingWindow constructor(private val context: Context) {
private var windowManager: WindowManager? = null
get() {
if (field == null) field = (context.getSystemService(WINDOW_SERVICE) as WindowManager)
return field
}
private var floatView: View =
LayoutInflater.from(context).inflate(R.layout.layout_floating_window, null)
private lateinit var layoutParams: WindowManager.LayoutParams
private var lastX: Int = 0
private var lastY: Int = 0
private var firstX: Int = 0
private var firstY: Int = 0
private var isShowing = false
private var touchConsumedByMove = false
private val onTouchListener = View.OnTouchListener { view, event ->
val totalDeltaX = lastX - firstX
val totalDeltaY = lastY - firstY
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> {
lastX = event.rawX.toInt()
lastY = event.rawY.toInt()
firstX = lastX
firstY = lastY
}
MotionEvent.ACTION_UP -> {
view.performClick()
}
MotionEvent.ACTION_MOVE -> {
val deltaX = event.rawX.toInt() - lastX
val deltaY = event.rawY.toInt() - lastY
lastX = event.rawX.toInt()
lastY = event.rawY.toInt()
if (abs(totalDeltaX) >= 5 || abs(totalDeltaY) >= 5) {
if (event.pointerCount == 1) {
layoutParams.x += deltaX
layoutParams.y += deltaY
touchConsumedByMove = true
windowManager?.apply {
updateViewLayout(floatView, layoutParams)
}
} else {
touchConsumedByMove = false
}
} else {
touchConsumedByMove = false
}
}
else -> {
}
}
touchConsumedByMove
}
init {
with(floatView) {
closeImageButton.setOnClickListener { dismiss() }
}
floatView.setOnTouchListener(onTouchListener)
layoutParams = WindowManager.LayoutParams().apply {
format = PixelFormat.TRANSLUCENT
flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
#Suppress("DEPRECATION")
type = when {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ->
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
else -> WindowManager.LayoutParams.TYPE_TOAST
}
gravity = Gravity.CENTER
width = WindowManager.LayoutParams.WRAP_CONTENT
height = WindowManager.LayoutParams.WRAP_CONTENT
}
}

Related

How I can Add Text inside Frame TabbedRenderer in Xamarin iOS

I am customizing Badge in TabbedPage. I have now added the red dot from inheriting UIView. However how can I Add Text inside that Frame. Xamarin iOS
MyTabbedPageRenderer.cs
public static class TabbarExtensions
{
readonly static int tabBarItemTag = 9999;
public static void addItemBadge(this UITabBar tabbar, int index)
{
if (tabbar.Items != null && tabbar.Items.Length == 0) return;
if (index >= tabbar.Items.Length) return;
removeItemBadge(tabbar, index);
var badgeView = new UIView();
badgeView.Tag = tabBarItemTag + index;
badgeView.Layer.CornerRadius = 7;
badgeView.BackgroundColor = UIColor.Red;
var tabFrame = tabbar.Frame;
var percentX = (index + 0.56) / tabbar.Items.Length;
var x = percentX * tabFrame.Width;
var y = tabFrame.Height * 0.05;
badgeView.Frame = new CoreGraphics.CGRect(x, y, 13, 13);
tabbar.AddSubview(badgeView);
//var badgeView = new UILabel();
//badgeView.Tag = tabBarItemTag + index;
//badgeView.BackgroundColor = UIColor.Red;
//var tabFrame = tabbar.Frame;
//var percentX = (index + 0.56) / tabbar.Items.Length;
//var x = percentX * tabFrame.Width;
//var y = tabFrame.Height * 0.05;
//badgeView.Text = "1";
//badgeView.TextAlignment = UITextAlignment.Center;
//badgeView.TextColor = UIColor.White;
//badgeView.Font = UIFont.SystemFontOfSize(10);
//tabbar.AddSubview(badgeView);
}
public static bool removeItemBadge(this UITabBar tabbar, int index)
{
foreach (var subView in tabbar.Subviews)
{
if (subView.Tag == tabBarItemTag + index)
{
subView.RemoveFromSuperview();
return true;
}
}
return false;
}
}
protected override void OnElementChanged(VisualElementChangedEventArgs e)
{
base.OnElementChanged(e);
MessagingCenter.Subscribe<object, int>(this, "Add", (obj, index) => {
TabBar.addItemBadge(index);
});
MessagingCenter.Subscribe<object, int>(this, "Remove", (obj, index) => {
TabBar.removeItemBadge(index);
});
}
MainView.xaml.cs
protected override void OnAppearing()
{
base.OnAppearing();
MessagingCenter.Send<object, int>(this, "Add", 2);
}
As in my code above I tried with UILabel. However I cannot set CornerRadius for Label
Summarize how I can Add Text inside Frame. Or how can I set CornerRadius for Lable in Xamarin iOS.
Thank you!
Description picture:
If I use UILabel, I cannot set CornerRadius
If I use UIView
For UILabel, you could set the CornerRadius using the following:
badgeView.Layer.CornerRadius = 7;
badgeView.Layer.MasksToBounds = true;//add this line
For more info, you could refer to masksToBounds.
Hope it works for you.

Skipping of inputs if user types fast

I am trying to create otp view where each item is individually editable, problem arises when user types fast, the input is skipped. I believe there is some delay in focus manager. Below is the code, let me know if there is any issues in the snippet itself
#Composable
#Preview
fun OtpLayout(modifier: Modifier = Modifier, otpLength: Int = 6) {
Row(horizontalArrangement = Arrangement.SpaceBetween, modifier = modifier.fillMaxWidth()) {
val focusManager = LocalFocusManager.current
val list = remember {
List(6) {
mutableStateOf(TextFieldValue(text = "", selection = TextRange(0)))
}
}
repeat(otpLength) { index ->
key(index) {
BasicTextField(
modifier = Modifier.onKeyEvent {
if (it.key == Key.Backspace && index > 0 && list[index].value.text.isEmpty()) {
focusManager.moveFocus(FocusDirection.Left)
}
true
},
maxLines = 1,
value = list[index].value,
textStyle = TextStyle(color = Color.White, fontSize = 16.sp),
keyboardOptions = KeyboardOptions.Default.copy(keyboardType = KeyboardType.Number),
onValueChange = { value ->
Log.e("OnValue Changed called", value.text)
if (value.text.length <= 1 && value.text.isDigitsOnly()) {
list[index].value = value
if (value.text != "" && index < otpLength - 1) {
focusManager.moveFocus(FocusDirection.Right)
} else if (value.text == "" && index > 0) {
focusManager.moveFocus(FocusDirection.Left)
}
} else if (list[index].value.text.length == 1 && index < otpLength - 1) {
list[index + 1].value = value.copy(text = value.text.last().toString())
focusManager.moveFocus(FocusDirection.Right)
}
},
decorationBox = { innerTextField ->
Box(contentAlignment = Alignment.Center,
modifier = Modifier
.size(width = 42.dp, height = 52.dp)
.border(width = 1.dp,
color = PrimaryColor,
shape = RoundedCornerShape(6.dp))
.background(color = Gray, shape = RoundedCornerShape(6.dp))) {
innerTextField()
}
}
)
}
}
}
}

How to display container contains tablelayout of 7 columns in center of the screen for all resolution screens in code name one

Currently we are displaying the container that contains the table layout with 7 columns in center of the screen in the 1280x800 pixels resolution.
But we need the same container displaying in the 1920x1200 pixels resolution in center of the screen.
Actually the container is displayed but the row data is missing. Is anything wrong in my code? Please help me how to resolve this one.
FlowLayout centerLayout = new FlowLayout();
centerLayout.setAlign(Component.CENTER);
centerLayout.setValign(Component.TOP);
Container centerContainer = new Container(centerLayout);
topTabelcontainer = new Container(new TableLayout(7, 1));
commonComponentsForm = new CommonComponentsForm();
eventPostSchedulesForm = commonComponentsForm.setEventPostSchedulesFormHeader(eventPostSchedulesForm, res, workerBreaksPreferences);
topTabelcontainer = commonComponentsForm.getEventInfoHeader(eventPostSchedulesForm, res, topTabelcontainer, "showroster");
filterLayoutContainer = this.getFilterBody();
postScheduleTableContainer = this.getEventPostScheduleTable();
TableLayout.Constraint postScheduleTableConstraint = new TableLayout.Constraint();
postScheduleTableConstraint.setHorizontalAlign(BorderLayout.CENTER_BEHAVIOR_SCALE);
postScheduleTableConstraint.setVerticalAlign(BorderLayout.CENTER_BEHAVIOR_SCALE);
topTabelcontainer.add(filterLayoutContainer);
headerContainer);
topTabelcontainer.add(postScheduleTableConstraint, postScheduleTableContainer);
centerContainer.add(topTabelcontainer);
centerContainer.setScrollableY(Boolean.TRUE);
centerContainer.setTactileTouch(Boolean.TRUE);
centerContainer.addPointerDraggedListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
float val = Display.getInstance().getDragSpeed(false);
boolean upperFlag = false;
if (Display.getInstance().isPortrait()) {
if (portRaitUpperBound < toralRecourdsCount)
upperFlag = true;
} else if (landScapeUpperBound < toralRecourdsCount)
upperFlag = true;
boolean lowerFlag = false;
if (Display.getInstance().isPortrait()) {
if ((portRaitLowerBound > 0 && portRaitLowerBound <= toralRecourdsCount))
lowerFlag = true;
} else if (landScapeLowerBound > 0 && landScapeLowerBound < toralRecourdsCount)
lowerFlag = true;
if (val >= 0.5 && scrollFlag) {
dragFlag = true;
if (upperFlag) {
scrollFlag = false;
setPageUpperAndLowerBound(Constants.NEXTFLAG);
postScheduleTableContainer.removeAll();
setEventPostScheduleTable(postScheduleTableContainer);
eventPostSchedulesForm.revalidate();
}
} else if (val <= -0.5 && scrollFlag) {
dragFlag = true;
if (lowerFlag) {
scrollFlag = false;
setPageUpperAndLowerBound(Constants.PREVIOUSFLAG);
postScheduleTableContainer.removeAll();
setEventPostScheduleTable(postScheduleTableContainer);
eventPostSchedulesForm.revalidate();
}
}
}
});
eventPostSchedulesForm.setUIID("workersListForm");
eventPostSchedulesForm.add(BorderLayout.CENTER, centerContainer);
commonComponentsForm.getFooterTag(eventPostSchedulesForm);
eventPostSchedulesForm.show();
}
public Container getEventPostSchedulesTableHeader(Container postSchedulesTableHeaderContainer) {
Label position = new Label(Constants.POSITION, searchingButtonImage);
Label name = new Label(Constants.NAME, searchingButtonImage);
Label callInOutLabel = new Label(Constants.CALLINOUT);
position.setTextPosition(LEFT);
name.setTextPosition(LEFT);
TextArea actualCallIn1 = null;
Label actualCallIn = null;
TextArea actualCallOut1 = null;
Label actualCallOut = null;
TextArea agencyWorker1 = null;
Label agencyWorker = null;
if (Display.getInstance().isPortrait()) {
actualCallIn1 = new TextArea(Constants.ACTUALCALLIN);
actualCallIn1.setEditable(false);
actualCallIn1.setFocusable(false);
actualCallIn1.setColumns(3);
actualCallIn1.setVerticalAlignment(Component.CENTER);
actualCallOut1 = new TextArea(Constants.ACTUALCALLOUT);
actualCallOut1.setEditable(false);
actualCallOut1.setFocusable(false);
actualCallOut1.setColumns(3);
actualCallOut1.setVerticalAlignment(Component.CENTER);
agencyWorker1 = new TextArea(Constants.AGENCYWORKER);
agencyWorker1.setEditable(false);
agencyWorker1.setFocusable(false);
agencyWorker1.setColumns(3);
agencyWorker1.setVerticalAlignment(Component.CENTER);
} else {
agencyWorker = new Label(Constants.AGENCYWORKER);
actualCallIn = new Label(Constants.ACTUALCALLIN);
actualCallOut = new Label(Constants.ACTUALCALLOUT);
}
Label workerBreak = new Label(" ");
position.setUIID("workerTableHeader");
name.setUIID("workerTableHeader");
callInOutLabel.setUIID("workerTableHeader");
if (Display.getInstance().isPortrait()) {
agencyWorker1.setUIID("workerTableHeader");
actualCallIn1.setUIID("workerTableHeader");
actualCallOut1.setUIID("workerTableHeader");
} else {
agencyWorker.setUIID("workerTableHeader");
actualCallIn.setUIID("workerTableHeader");
actualCallOut.setUIID("workerTableHeader");
}
workerBreak.setUIID("workerTableHeader");
if (Display.getInstance().isPortrait()) {
postSchedulesTableHeaderContainer.addComponent(getTableConstraint(16, 8), position);
postSchedulesTableHeaderContainer.addComponent(getTableConstraint(15, 8), name);
postSchedulesTableHeaderContainer.addComponent(getTableConstraint(24, 8), callInOutLabel);
postSchedulesTableHeaderContainer.addComponent(getTableConstraint(13, 8), actualCallIn1);
postSchedulesTableHeaderContainer.addComponent(getTableConstraint(13, 8), actualCallOut1);
postSchedulesTableHeaderContainer.add(getTableConstraint(13, 8), agencyWorker1);
if (workerBreaksPreferences.getAllowbreaks() != null && !"".equals(workerBreaksPreferences.getAllowbreaks()) && "1".equals(workerBreaksPreferences.getAllowbreaks()))
postSchedulesTableHeaderContainer.addComponent(getTableConstraint(6, 8), workerBreak);
} else {
postSchedulesTableHeaderContainer.addComponent(getTableConstraint(13, 10), position);
postSchedulesTableHeaderContainer.addComponent(getTableConstraint(18, 10), name);
postSchedulesTableHeaderContainer.addComponent(getTableConstraint(20, 10), callInOutLabel);
postSchedulesTableHeaderContainer.addComponent(getTableConstraint(13, 10), actualCallIn);
postSchedulesTableHeaderContainer.addComponent(getTableConstraint(13, 10), actualCallOut);
postSchedulesTableHeaderContainer.addComponent(getTableConstraint(16, 10), agencyWorker);
if (workerBreaksPreferences.getAllowbreaks() != null && !"".equals(workerBreaksPreferences.getAllowbreaks()) && "1".equals(workerBreaksPreferences.getAllowbreaks()))
postSchedulesTableHeaderContainer.addComponent(getTableConstraint(7, 10), workerBreak);
}
return postSchedulesTableHeaderContainer;
}
public Container getEventPostScheduleTable() {
List < WorkerBean > eventPostSchedulesList = null;
roasterDao = RoasterDao.getInstance();
if (Display.getInstance().isPortrait()) {
eventPostSchedulesList = roasterDao.getEventPostSchedulesDetails(positionFilterValue, nameFilterValue, portRaitLowerBound, portRaitPageSize);
} else {
eventPostSchedulesList = roasterDao.getEventPostSchedulesDetails(positionFilterValue, nameFilterValue, landScapeLowerBound, landScapePageSize);
}
int tableRowCount = Constants.INITIALTABLEROWS;
boolean pagingFlag = false;
int eventPostScheduleCount = roasterDao.getEventPostSchedulesCount(positionFilterValue, nameFilterValue);
this.toralRecourdsCount = eventPostScheduleCount;
FlowLayout centerLayout = new FlowLayout();
centerLayout.setAlign(Component.CENTER);
postScheduleTableContainer = new Container(centerLayout);
postScheduleTableContainer.setUIID("tableBodyContainer");
if (eventPostSchedulesList.size() > landScapePageSize) {
tableRowCount = landScapePageSize + 1;
} else {
tableRowCount = eventPostSchedulesList.size() + 1;
}
Container borderTopPagingContainer = new Container(new BorderLayout());
if (eventPostScheduleCount > landScapePageSize) {
pagingFlag = true;
if (Display.getInstance().isPortrait()) {
borderTopPagingContainer = this.setHeaderPaging(eventPostScheduleCount, portRaitLowerBound, portRaitUpperBound, res);
} else {
borderTopPagingContainer = this.setHeaderPaging(eventPostScheduleCount, landScapeLowerBound, landScapeUpperBound, res);
}
}
if (pagingFlag) {
tableRowCount = tableRowCount + 1;
}
int columnCount = 6;
if (workerBreaksPreferences.getAllowbreaks() != null && !"".equals(workerBreaksPreferences.getAllowbreaks()) && "1".equals(workerBreaksPreferences.getAllowbreaks()))
columnCount++;
Container postSchedulesListContainer = new Container(new TableLayout(tableRowCount, columnCount));
if (pagingFlag) {
TableLayout.Constraint postSchedulesListConstraint1 = new TableLayout.Constraint();
postSchedulesListConstraint1.setHorizontalSpan(columnCount);
postSchedulesListContainer.add(postSchedulesListConstraint1, borderTopPagingContainer);
}
postSchedulesListContainer = this.getEventPostSchedulesTableHeader(postSchedulesListContainer);
String callInDBValue = "";
String callOutDBValue = "";
String actCallInDBValue = "";
String actCallOutDBValue = "";
Label position = null;
Label name = null;
Label callInOutLabel = null;
Label actualCallIn = null;
Label actualCallOut = null;
TextField agencyWorker = null;
Label workerBreak = null;
for (WorkerBean eventPostSchedules: eventPostSchedulesList) {
callInDBValue = "";
if (eventPostSchedules != null) {
if (eventPostSchedules.getCallIn().length() > 10)
callInDBValue = eventPostSchedules.getCallIn().substring(10).trim();
else {
if (Constants.PLATFORMNAME.equals(Display.getInstance().getPlatformName()))
callInDBValue = " ";
else
callInDBValue = " ";
}
}
callOutDBValue = "";
if (eventPostSchedules != null) {
if (eventPostSchedules.getCallOut().length() > 10)
callOutDBValue = eventPostSchedules.getCallOut().substring(10).trim();
else {
if (Constants.PLATFORMNAME.equals(Display.getInstance().getPlatformName()))
callOutDBValue = " ";
else
callOutDBValue = " ";
}
}
actCallInDBValue = "";
if (eventPostSchedules != null) {
if (eventPostSchedules.getActCallIn().length() > 10)
actCallInDBValue = eventPostSchedules.getActCallIn().substring(10).trim();
else
actCallInDBValue = eventPostSchedules.getActCallIn().trim();
}
actCallOutDBValue = "";
if (null != eventPostSchedules) {
if (eventPostSchedules.getActCallOut().length() > 10)
actCallOutDBValue = eventPostSchedules.getActCallOut().substring(10).trim();
else
actCallOutDBValue = eventPostSchedules.getActCallOut().trim();
}
callInDBValue = ((callInDBValue.trim().length() < 8) ? " ".concat(callInDBValue) : callInDBValue) + ((callOutDBValue.trim().equals("")) ? callOutDBValue : " - " + callOutDBValue);
position = new Label(eventPostSchedules.getPersonnelType());
name = new Label(eventPostSchedules.getName());
callInOutLabel = new Label(callInDBValue);
actualCallIn = new Label(actCallInDBValue);
actualCallIn.setFocusable(Boolean.TRUE);
actualCallIn.addPointerPressedListener(createActualCallChangeListener(actualCallIn, eventPostSchedules.getSerialId(), Constants.ACTUALCALLINFLAG, eventPostSchedules.getName(), eventPostSchedules.getActCallIn(), eventPostSchedules.getActCallOut(), eventPostSchedules.getActCallIn()));
actualCallOut = new Label(actCallOutDBValue);
actualCallOut.setFocusable(Boolean.TRUE);
actualCallOut.addPointerPressedListener(createActualCallChangeListener(actualCallOut, eventPostSchedules.getSerialId(), Constants.ACTUALCALLOUTFLAG, eventPostSchedules.getName(), eventPostSchedules.getActCallIn(), eventPostSchedules.getActCallOut(), eventPostSchedules.getActCallOut()));
agencyWorker = new TextField(eventPostSchedules.getAgencyWorker(), null, 5, TextArea.ANY);
position.setUIID("workersList");
name.setUIID("workersList");
callInOutLabel.setUIID("workersList");
actualCallIn.setUIID("workersListEditable");
actualCallOut.setUIID("workersListEditable");
agencyWorker.setUIID("workersListEditable");
workerBreak.setUIID("workersList");
if (Display.getInstance().isPortrait()) {
postSchedulesListContainer.addComponent(getTableConstraint(16, 8), position);
postSchedulesListContainer.addComponent(getTableConstraint(15, 8), name);
postSchedulesListContainer.addComponent(getTableConstraint(24, 8), callInOutLabel);
postSchedulesListContainer.addComponent(getTableConstraint(13, 8), actualCallIn);
postSchedulesListContainer.addComponent(getTableConstraint(13, 8), actualCallOut);
postSchedulesListContainer.addComponent(getTableConstraint(13, 8), agencyWorker);
if (workerBreaksPreferences.getAllowbreaks() != null && !"".equals(workerBreaksPreferences.getAllowbreaks()) && "1".equals(workerBreaksPreferences.getAllowbreaks()))
postSchedulesListContainer.addComponent(getTableConstraint(6, 8), workerBreak);
} else {
postSchedulesListContainer.addComponent(getTableConstraint(13, 10), position);
postSchedulesListContainer.addComponent(getTableConstraint(18, 10), name);
postSchedulesListContainer.addComponent(getTableConstraint(20, 10), callInOutLabel);
postSchedulesListContainer.addComponent(getTableConstraint(13, 10), actualCallIn);
postSchedulesListContainer.addComponent(getTableConstraint(13, 10), actualCallOut);
postSchedulesListContainer.addComponent(getTableConstraint(16, 10), agencyWorker);
if (workerBreaksPreferences.getAllowbreaks() != null && !"".equals(workerBreaksPreferences.getAllowbreaks()) && "1".equals(workerBreaksPreferences.getAllowbreaks()))
postSchedulesListContainer.addComponent(getTableConstraint(7, 10), workerBreak);
}
}
postScheduleTableContainer.add(postSchedulesListContainer);
return postScheduleTableContainer;
}
}
}
public TableLayout.Constraint getTableConstraint(int widthPercent, int heightPercent) {
TableLayout.Constraint tableConstraint = new TableLayout.Constraint();
tableConstraint.setWidthPercentage(widthPercent);
tableConstraint.setHeightPercentage(heightPercent);
return tableConstraint;
}
}
Don't use flow layout for large dynamic data. You border layout with center constraint or absolute center.
Flow layout is overly simplistic and shouldn't be used for complex structures since Codename One doesn't reflow. There is a big discussion of that in the developer guide.

Error #1069: Property Pertanyaan0 not found on String and there is no default value

I stuck here please help, i'm new in flash, using adobe flash cs5.5
Here's the code :
import flash.net.URLLoaderDataFormat;
import flash.events.DataEvent;
stop();
alert_mc.visible = false;
alert_mc.ok_btn.visible = false;
var score:Number = 0;
var jawaban;
var nextQst:Number = 0;
var i:Number = 0;
a_btn.addEventListener(MouseEvent.CLICK,btna);
function btna(ev:MouseEvent):void
{
cekJawaban("a");
}
b_btn.addEventListener(MouseEvent.CLICK,btnb);
function btnb(ev:MouseEvent):void
{
cekJawaban("b");
}
c_btn.addEventListener(MouseEvent.CLICK,btnc);
function btnc(ev:MouseEvent):void
{
cekJawaban("c");
}
d_btn.addEventListener(MouseEvent.CLICK,btnd);
function btnd(ev:MouseEvent):void
{
cekJawaban("d");
}
var qvar_lv:URLLoader = new URLLoader();
qvar_lv.dataFormat = URLLoaderDataFormat.TEXT;// Step 1
qvar_lv.load(new URLRequest("DaftarSoal.txt")); // Step 2
qvar_lv.addEventListener(Event.COMPLETE, onComplete); // Step 3
function onComplete (event:Event):void // Step 4
{
var faq:String = event.target.data; // Step 5
trace("Success"+faq);
if (faq["Pertanyaan"+i] != undefined) {
no_txt.text = "PERTANYAAN KE-"+i;
soal_txt.text = faq["Pertanyaan"+i]; ja_txt.text = faq["a"+i];
jb_txt.text = faq["b"+i];
jc_txt.text = faq["c"+i];
jd_txt.text = faq["d"+i];
jawaban =faq["benar"+i];
} else {
gotoAndStop(3);
skor_txt.text = score+"";
teks_txt.text = "Score akhir kamu :";
}
}
function cekJawaban(val) {
alert_mc.visible = true;
if (val != jawaban) {
alert_mc.alert_txt.text = "jawaban kamu salah, score anda berkurang 50 points";
score = score-50;
alert_mc.ok_btn.addEventListener(MouseEvent.CLICK,btnok);
function btnok(ev:MouseEvent):void
{
nextQst = i+1;
alert_mc.visible = false;
}
} else {
score = score+100;
alert_mc.alert_txt.text = "jawaban kamu benar, score anda bertambah 100 points";
alert_mc.ok_btn.addEventListener(MouseEvent.CLICK,btnok2);
function btnok2(ev:MouseEvent):void
{
nextQst = i+1;
alert_mc.visible = false;
}
trace(score);
}
}
Error #1069:
Property Pertanyaan0 not found on String and there is no default value.
at revisi_fla::Symbol5_68/onComplete()
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at flash.net::URLLoader/onComplete()

JavaFX, apply setStyle to all LineCharts in ObservableList

I have ObservableList<LineChart> backCharts. Also I have class StackChartSeries to compare data's scale. Depending on that I add new backchart with new scale or add series to existed backchart.
Applying style to chart must work with every chart of the specified scale. But it works only with the first chart of the specified scale.
Code next:
public class StackChart extends StackPane {
private LineChart baseChart;
private final ObservableList<LineChart> backCharts = FXCollections.observableArrayList();
private final double yAxisWidth = 60;
private final AnchorPane details;
private final double yAxisSeparation = 20;
private double strokeWidth = 0.5;
private int size = 0;
public StackChart(LineChart baseChart) {
this(baseChart, null);
}
public StackChart(LineChart baseChart, Double strokeWidth) {
if (strokeWidth != null) {
this.strokeWidth = strokeWidth;
}
this.baseChart = baseChart;
baseChart.setCreateSymbols(false);
baseChart.setLegendVisible(false);
baseChart.getXAxis().setAutoRanging(false);
baseChart.getXAxis().setAnimated(false);
baseChart.getXAxis().setStyle("-fx-font-size:" + 18);
baseChart.getYAxis().setAnimated(false);
baseChart.getYAxis().setStyle("-fx-font-size:" + 18);
setFixedAxisWidth(baseChart);
setAlignment(Pos.CENTER_LEFT);
backCharts.addListener((Observable observable) -> rebuildChart());
details = new AnchorPane();
bindMouseEvents(baseChart, this.strokeWidth);
rebuildChart();
}
private void bindMouseEvents(LineChart baseChart, Double strokeWidth) {
getChildren().add(details);
details.prefHeightProperty().bind(heightProperty());
details.prefWidthProperty().bind(widthProperty());
details.setMouseTransparent(true);
setOnMouseMoved(null);
setMouseTransparent(false);
final Axis xAxis = baseChart.getXAxis();
final Axis yAxis = baseChart.getYAxis();
final Line xLine = new Line();
final Line yLine = new Line();
yLine.setFill(Color.GRAY);
xLine.setFill(Color.GRAY);
yLine.setStrokeWidth(strokeWidth/2);
xLine.setStrokeWidth(strokeWidth/2);
xLine.setVisible(false);
yLine.setVisible(false);
final Node chartBackground = baseChart.lookup(".chart-plot-background");
for (Node n: chartBackground.getParent().getChildrenUnmodifiable()) {
if (n != chartBackground && n != xAxis && n != yAxis) {
n.setMouseTransparent(true);
}
}
chartBackground.setCursor(Cursor.CROSSHAIR);
chartBackground.setOnMouseEntered((event) -> {
chartBackground.getOnMouseMoved().handle(event);
xLine.setVisible(true);
yLine.setVisible(true);
details.getChildren().addAll(xLine, yLine);
});
chartBackground.setOnMouseExited((event) -> {
xLine.setVisible(false);
yLine.setVisible(false);
details.getChildren().removeAll(xLine, yLine);
});
chartBackground.setOnMouseMoved(event -> {
double x = event.getX() + chartBackground.getLayoutX();
double y = event.getY() + chartBackground.getLayoutY();
xLine.setStartX(65);
xLine.setEndX(details.getWidth()-10);
xLine.setStartY(y+5);
xLine.setEndY(y+5);
yLine.setStartX(x+5);
yLine.setEndX(x+5);
yLine.setStartY(12);
yLine.setEndY(details.getHeight()-28);
});
}
private void setFixedAxisWidth(LineChart chart) {
chart.getYAxis().setPrefWidth(yAxisWidth);
chart.getYAxis().setMaxWidth(yAxisWidth);
}
private void rebuildChart() {
getChildren().clear();
getChildren().add(resizeBaseChart(baseChart));
for (LineChart lineChart : backCharts) {
getChildren().add(resizeBackgroundChart(lineChart));
}
getChildren().add(details);
}
private Node resizeBaseChart(LineChart lineChart) {
HBox hBox = new HBox(lineChart);
hBox.setAlignment(Pos.CENTER_LEFT);
hBox.prefHeightProperty().bind(heightProperty());
hBox.prefWidthProperty().bind(widthProperty());
lineChart.minWidthProperty().bind(widthProperty().subtract((yAxisWidth+yAxisSeparation)*backCharts.size()));
lineChart.prefWidthProperty().bind(widthProperty().subtract((yAxisWidth+yAxisSeparation)*backCharts.size()));
lineChart.maxWidthProperty().bind(widthProperty().subtract((yAxisWidth+yAxisSeparation)*backCharts.size()));
return lineChart;
}
private Node resizeBackgroundChart(LineChart lineChart) {
HBox hBox = new HBox(lineChart);
hBox.setAlignment(Pos.CENTER_LEFT);
hBox.prefHeightProperty().bind(heightProperty());
hBox.prefWidthProperty().bind(widthProperty());
hBox.setMouseTransparent(true);
lineChart.minWidthProperty().bind(widthProperty().subtract((yAxisWidth + yAxisSeparation) * backCharts.size()));
lineChart.prefWidthProperty().bind(widthProperty().subtract((yAxisWidth + yAxisSeparation) * backCharts.size()));
lineChart.maxWidthProperty().bind(widthProperty().subtract((yAxisWidth + yAxisSeparation) * backCharts.size()));
lineChart.translateXProperty().bind(baseChart.getYAxis().widthProperty());
lineChart.getYAxis().setTranslateX((yAxisWidth + yAxisSeparation) * backCharts.indexOf(lineChart));
return hBox;
}
private LineChart prepareLineChart(String seriesName){
NumberAxis yAxis = new NumberAxis();
NumberAxis xAxis = new NumberAxis();
// xAxis
xAxis.setAutoRanging(false);
xAxis.setVisible(false);
xAxis.setOpacity(0.0);
xAxis.lowerBoundProperty().bind(((NumberAxis) baseChart.getXAxis()).lowerBoundProperty());
xAxis.upperBoundProperty().bind(((NumberAxis) baseChart.getXAxis()).upperBoundProperty());
xAxis.tickUnitProperty().bind(((NumberAxis) baseChart.getXAxis()).tickUnitProperty());
// yAxis
yAxis.setSide(Side.RIGHT);
yAxis.setLabel(seriesName);
// create chart
LineChart lineChart = new LineChart(xAxis, yAxis);
lineChart.setAnimated(false);
lineChart.setLegendVisible(false);
setFixedAxisWidth(lineChart);
return lineChart;
}
public void addSeries(List<StackChartSeries> series){
Collections.sort(series, (x, y) -> (int) (x.getMaxY() - y.getMaxY()));
LineChart lineChart = null;
size = series.size();
for (int i = 0; i < size; i++) {
if (i == 0 || series.get(i).getMaxY() / series.get(i-1).getMaxY() >= 10
|| series.get(i).getMaxY() / series.get(i-1).getMaxY() <= 0.1
|| Math.abs(series.get(i).getMaxY() - series.get(i-1).getMaxY()) >= 900
) {
lineChart = prepareLineChart("Scale" + i);
//new chart with new scale
backCharts.add(lineChart);
}
lineChart.getData().add(series.get(i).getSeries());
}
int j = 0;
for (LineChart chart : backCharts) {
styleBackChart(chart);
//HERE
setLineStyle(chart, j+3);
}
}
private void styleBackChart(LineChart lineChart) {
setStyle(lineChart);
Node contentBackground = lineChart.lookup(".chart-content").lookup(".chart-plot-background");
contentBackground.setStyle("-fx-background-color: transparent;");//
lineChart.setVerticalZeroLineVisible(false);
lineChart.setHorizontalZeroLineVisible(false);
lineChart.setVerticalGridLinesVisible(false);
lineChart.setHorizontalGridLinesVisible(false);
lineChart.setCreateSymbols(false);
lineChart.getXAxis().setStyle("-fx-font-size:" + 18);
lineChart.getYAxis().setStyle("-fx-font-size:" + 18);
}
private void setStyle(LineChart chart) {
chart.getYAxis().lookup(".axis-label").setStyle("-fx-font-size: 24;");
Node seriesLine = chart.lookup(".chart-series-line");
seriesLine.setStyle("-fx-stroke-width: " + strokeWidth + ";");
}
public Node getLegend() {
HBox hbox = new HBox();
final CheckBox baseChartCheckBox = new CheckBox(baseChart.getYAxis().getLabel());
baseChartCheckBox.setSelected(true);
baseChartCheckBox.setDisable(true);
baseChartCheckBox.getStyleClass().add("readonly-checkbox");
baseChartCheckBox.setOnAction(event -> baseChartCheckBox.setSelected(true));
hbox.getChildren().add(baseChartCheckBox);
for (final LineChart lineChart : backCharts) {
CheckBox checkBox = new CheckBox(lineChart.getYAxis().getLabel());
checkBox.setSelected(true);
checkBox.setOnAction(event -> {
if (backCharts.contains(lineChart)) {
backCharts.remove(lineChart);
} else {
backCharts.add(lineChart);
}
});
hbox.getChildren().add(checkBox);
}
hbox.setAlignment(Pos.CENTER);
hbox.setSpacing(20);
hbox.setStyle("-fx-padding: 0 10 20 10");
return hbox;
}
private void setLineStyle (LineChart chart, Integer k) {
Node seriesLine = chart.lookup(".chart-series-line");
seriesLine.setStyle(" -fx-stroke-dash-array: " + k + " 5 15 5;");
}
}
StackChartSeries.java:
import javafx.scene.chart.XYChart;
import org.apache.commons.lang.ArrayUtils;
import java.util.Arrays;
import java.util.Collections;
import java.util.Optional;
public class StackChartSeries {
private XYChart.Series series;
private final double[] xValues;
private final double[] yValues;
private Optional<Double> maxY;
public StackChartSeries(double[] xValues, double[] yValues) {
this.xValues = xValues;
this.yValues = yValues;
}
public XYChart.Series getSeries() {
return series != null ? series : (series = prepareSeries(xValues, yValues));
}
private static XYChart.Series<Number, Number> prepareSeries( double[] xValues, double[] yValues) {
XYChart.Series<Number, Number> series = new XYChart.Series<>();
for (int i = 0; i < yValues.length; i++){
series.getData().add(new XYChart.Data(xValues[i], yValues[i]));
}
return series;
}
public double getMaxY(){
if (maxY != null){
return maxY.get();
}
else {
Double d = C?ollections.max(Arrays.asList(ArrayUtils.toObject(yValues)));
maxY = Optional.of(d);
return maxY.get();
}
}
public double[] getXValues() {
return xValues;
}
public double[] getYValues() {
return yValues;
}
}

Resources