Automatic update of Button text on change - scala

I'm currently learning scala, and making an encryption program with a basic scala swing UI.
I added 2 swing buttons which text is held by 2 var.
The code looks like this :
var encText = "Encrypt"
var decText = "Decrypt"
def top = new MainFrame {
title = "Data Guardian"
minimumSize = new Dimension(500, 200)
contents = new GridPanel(2, 2) {
hGap = 3; vGap = 3
contents += new Button {
text = encText
reactions += {
case ButtonClicked(_) => Main.startEnc
}
}
contents += new Button {
text = decText
reactions += {
case ButtonClicked(_) => Main.startDec
}
}
}
size = new Dimension(150, 40)
}
Those "text" var will be changed often during the encryption/decryption process by various methods, but when they do change, the text displayed on the buttons doesn't.
I'd like to know a way to make the displayed text of the buttons automatically change when the var that holds that text changes.
Thanks a lot for your insight :)

Make the strings private and write getters/setters that change the button text as a side-effect.
You'll need to give the buttons names, rather than having anonymous instances as you do above.

Related

How to add and edit a short answer in multiple google forms

So I have multiple google forms (around 20 forms), that I need to do 2 things to them:
1- These 20 forms are placed in a folder in my google drive. I need to add more like an "Access code" where users will have to insert in order to continue the solving the quiz.
The way I did that was to add a "short answer" question to "section 1" of the quiz asking "Enter your Access Code", add "response validation", "Regular expression" and "Pattern". Also making this a "required question". This should look something like the below picture
Example of google form
So is it possible to have a scriptto add this question to all 20 forms
2- The "access code" in these google forms will have to be updated frequently, so I don' want to be updating the "Pattern" manually for each form, is t possible to have a google script to edit the value of the pattern for each form
Thanks in advance guys :)
I managed to solve this issue that I was having, through looking for different codes and here are the codes that I used.
N.B. The codes might not be very clean as I was copying them from other parts/projects, but they have worked for me
1- Update the 20 forms with adding the access code question, I figured it was not possible to add a question at a certain position in the google form, however I can add a question at the end of the form and then move this item to the position I want:
function AddAccesscodeQ() {
var filess = DriveApp.getFolderById("Drive id>").getFiles();
while (filess.hasNext()) {
var file = filess.next();
var form = FormApp.openById(file.getId());
var sectionIndex= 0; // Please set the index you want to insert.
//I added a "sample item" to be moved and edited later
var newItemQ = form.addTextItem().setTitle("New sample item").getIndex(); // New sample item
// I added a Pagebreak that also should be moved after the questions "Enter Your Access Code"
var newItemPB = form.addPageBreakItem().getIndex();
var items = form.getItems(FormApp.ItemType.PAGE_BREAK);
var sections = [0];
for (var i = 0; i < items.length; i++) {
// I pushed the items in the google form twice downwards, to be able to move the "sample item" and "Page break" to the top of the form
sections.push(items[i].getIndex());
sections.push(items[i].getIndex());
}
var insertIndex = sections[sectionIndex + 1] || null;
if (insertIndex) {
// Here I moved the 2 new items to the desired positions
form.moveItem(newItemQ, 0);
form.moveItem(newItemPB, 1);
}
// Here I am going to edit the "Sample Question" to be as desired
var itemss = form.getItems();
var itemID = itemss[0].getId();
var itemse = form.getItemById(itemID).asTextItem()
.setTitle('Enter Your Access Code').setRequired(true);
//Create validation rule
var validation = FormApp.createTextValidation()
.setHelpText('Invalid Code')
.requireTextMatchesPattern("<Access Code>")
.build();
itemse.setValidation(validation);
}
}
2- The second problem was that I later might need to change this access code to a new one for the 20 forms
function UpdateAccessCode() {
var filesPhCH = DriveApp.getFolderById("<Drive ID>").getFiles();
while (filesPhCH.hasNext()) {
var file = filesPhCH.next();
var form = FormApp.openById(file.getId());
var items = form.getItems();
//Loop through the items and list them
for (var i = 0;i<items.length;i++){
var item = items[i];
var itemID = item.getId();
var itemtitle = item.getTitle();
var itemindex = item.getIndex();
// I found no need to continue the for loop since the items that need modification are at the top of the form
if (itemindex == 0){
break;
}
}
//Select the question you want to update
var itemse = form.getItemById(itemID).asTextItem()
.setTitle('Enter Your Access Code');
//Create validation rule
var validation = FormApp.createTextValidation()
//.setTitle('Enter Your Access Code');
.setHelpText('Invalid Code')
.requireTextMatchesPattern("<Enter the new Access Code>")
.build();
itemse.setValidation(validation);
}
}
I hope this might help someone as it has saved a lot of time for me ;)

Jetpack compose LazyColumn or Scrollable Column and IME padding for TextField doesn't work

I am trying to set a list if text fields, and when user set the focus on one text field at the bottom I expect that the user can see the appearing IME soft keyboard and the text field being padded according to the configuration set in my manifest file android:windowSoftInputMode="adjustPan", but it doesn't work the first time, it works only when some of the listed textfield have already a focus.
Behavior in video.
My code in onCreate method.
// Turn off the decor fitting system windows, which allows us to handle insets,
// including IME animations
WindowCompat.setDecorFitsSystemWindows(window, false)
setContent {
// Provide WindowInsets to our content. We don't want to consume them, so that
// they keep being pass down the view hierarchy (since we're using fragments).
ProvideWindowInsets(consumeWindowInsets = false) {
MyApplicationTheme {
// A surface container using the 'background' color from the theme
Surface(color = MaterialTheme.colors.background, modifier = Modifier.systemBarsPadding()) {
Column(modifier = Modifier.fillMaxHeight()) {
val list: List<#Composable () -> Unit> = (1..10).map {
{
Text(text = "$it")
Divider()
TextField(value = "", onValueChange = {}, modifier = Modifier.navigationBarsWithImePadding(),)
}
}
LazyColumn(modifier = Modifier.fillMaxSize().weight(1F)) {
itemsIndexed(list) { index, inputText ->
inputText()
}
}
}
}
}
}
}
If your problem is going on, check Insets for Jetpack Compose.
Only add this dependency:
implementation 'com.google.accompanist:accompanist-insets:{insetsVersion}'
and use Modifier.imePadding() or the custom solution:
#Composable
fun ImeAvoidingBox() {
val insets = LocalWindowInsets.current
val imeBottom = with(LocalDensity.current) { insets.ime.bottom.toDp() }
Box(Modifier.padding(bottom = imeBottom))
}

how to check image value with tab host

Ok so i will try to explain what im trying to do as clearly as possible with examples.
i have a tabhost with 5 tabs (engine,body,photo,spec,colors).
the upper portion of the xml layout(car.xml) has an imageView1.
and the and the lower portion of the layout car.xml holds the tabs. each tab calls an intent.
such as "" car.this.coupe_specs = new Intent(this, coupe_tab.class); ""
and coupe_tab.xml layout has 1 textView.
now what i am trying to do is change the text in the textView field in coupe_tab.xml
after checking the id: of the imageView1 on the car.xml.
so basicly i want to from car.java check the value of a ImageView in car.java and if true change the text in the TextView in coupe_tab.java the problem i seem to be having is doing all this inside a onItemSelected function.
non functional example just to help you under stand my wants
example:
import com.myexample._coupe_tab;
public void onItemSelected(AdapterView<?> example int view) {
if ("car.png").equals imageView1 {
textView1 = "example text 1";
}
else if ("car2.png).equals imageView1 {
textView1 = "example text 2";
}
else {
// do something else
}

Can't Get Multiple Charts (Google Visualization) on Multiple Tabs (GWT TabPanel)

I need to display an unknown quantity of tabs each with an unknown quantity of graphs (Google Visualizations). I have created "Tab" and "Graph" classes and Tab contains an ArrayList.
TabWrappers extends FlexTable and is currently empty. It's a place holder at the moment, but the behavior does not change if I use FlexTable rather than TabWrapper.
The code below, minus the section that adds Tab2 works perfectly for creating 1 tab populated with graphs. When adding the 2nd tab both tabs are displayed and named correctly but neither have graphs.
public class SomeClass {
...
DataTable data = response.getDataTable();
DataView result;
Options options = createOptions();
ArrayList<Tab> displayTab = new ArrayList<Tab>();
Tab t;
ArrayList<Graph> graphList = new ArrayList<Graph>();
Graph g;
t = new Tab();
g = new Graph();
result = DataView.create(data);
result.setRows(new int[]{0, 2, 4, 6});
g.setGraphType(new PieChart(result, options));
graphList.add(g);
g = new Graph();
result = DataView.create(data);
result.setRows(new int[]{1, 3, 5, 7});
g.setGraphType(new PieChart(result, options));
graphList.add(g);
g = new Graph();
result = DataView.create(data);
g.setGraphType(new PieChart(result, options));
graphList.add(g);
t.setTabName("Tab1");
t.setGraphs(graphList);
displayTab.add(t);
// Add a 2nd tab
t = new Tab();
t.setTabName("Tab2");
t.setGraphs(graphList);
displayTab.add(t);
TabWrapper tabWrapper;
for (Tab tX : displayTab){
int row = 0, col = 0, maxCol = 2;
tabWrapper = new TabWrapper();
for (Graph gX : tX.getGraphs()) {
col = tX.getGraphs().indexOf(gX) - (row * maxCol);
tabWrapper.setWidget(row, col, gX.getGraphType().asWidget());
if (++col == maxCol) {
row++;
}
}
tabPanel.add(tabWrapper, tX.getTabName());
}
...
}
When you use tabs in GWT, the panels held in each tab seem to be lazy loaded and aren't completely set up until the user clicks on each tab.
In particular, the tab containers will have zero widths and heights (the error logs will probably be giving an error about containers having zero width) so the graph drawing will fail and leave an empty space.
What you need to do (and is probably good practice anyway) is to lazy load the contents of the tabs too so that the graph is loaded only when the tab is fully set up. This can be done by removing the call the t.setGraphs(...) and adding a selection handler that does it instead:
tabPanel.addSelectionHandler(new SelectionHandler<Integer> () {
public void onSelection(SelectionEvent<Integer> event) {
// Pseudocode:
// n = event.getSelectedItem()
// t = displayTab[n]
// g = graphList[n]
// t.setGraphs(g)
}
});
so that graphs are added and drawn only when the tab is selected.
You'll probably also want to call
tabPanel.selectTab(0);
to force a selection of the first tab after the selection handler is in place.
I had the same issues that you describe and this resolved it.

How to find if user has selectedwhole text or a part of text in tiny mce

I want to check the node of the selected text. If it is span, another function will edit the classes applied to it. If it is same as the parent node, then the code will wrap the selection in span and set its styles. The problem here I'm facing is, how to determine, if user has selected the whole text inside the editor or only some text. If user selects the whole text, I want to apply the styles to the parent node instead of adding a new span and styles to it. Below is my code -
var ed=tinyMCE.getInstanceById('textAreaId');
var sel = ed.selection.getContent();
if(trim(sel)!="") {
//get the node of the selection
var thisNode=tinyMCE.activeEditor.selection.getStart().nodeName;
ed_Property=propertyName;
ed_PropertyVal=propertyValue;
//get the root node inside editor
var parentNode=tinyMCE.activeEditor.getBody().firstChild.nodeName;
if(thisNode=="SPAN") {
nodeclass=$(tinyMCE.activeEditor.selection.getNode()).attr('class');
//edit span properties
editSpanProperties(nodeclass,propertyName,propertyValue);
}
else if(thisNode==parentNode) {
var elmType="span";
var Spanid1=createSpanId(targetToStyle,elmType);
Spanid=targetToStyle+"_"+elmType+"_"+Spanid1;
var strStyle=ed_Property+":"+ed_PropertyVal;
//wrap selection in a span
sel = "<span id='"+Spanid+"' style='"+strStyle+"'>" + sel + "</span>";
//set content
ed.selection.setContent(sel);
//retain the selection
ed.selection.select(ed.dom.select('#'+Spanid)[0],false);
}
else {
//here I need to check if user has selected whole text and set properties
setStylesOnEditor(templateSection,propertyName,propertyValue);
}//if ends
}
else if(trim(sel)=="") {
alert('No text selected');
}
how to determine, if user has selected
the whole text inside the editor or
only some text.
You need to compare the selected text with the editors content:
var content_editor = $(ed.getBody()).text();
var content_selection = ed.selection.getContent({format : 'text'});
// now compare both either characterwise or as whole string,
// you might need to strip whitespace characters from the strings!
// and do what you want to do in each case