Show labels in JavaFX only when a CheckBox is checked - user-interface

I´m trying to configure a small GUI with JavaFX. At the start there is the possibility to give some information regarding a date and a time (when you´ve worked) with two textfields.
Underneath there is a Checkbox which you can check if you want to “Choose more days?”.
Now there are two possibilities I want to enable:
a) When you check the box you can see more textfields to grant more information about different dates
b) When you check the box by mistake, the textfields should disappear when the box is unchecked and the screen is the same like at the start
I have already the following part of the code. It is already working that I can see more textfields, when I check the box, but when the box is unchecked, the textfields are still there.
CheckBox moreDays= new CheckBox("Choose more days?");
EventHandler<ActionEvent> showMoreLabels = new EventHandler<ActionEvent>() {
public void handle(ActionEvent e)
{
if (moreDays.isSelected()) {
Label dayTwo= new Label("Day Two:");
pane.add(dayTwo, 0, 7);
final TextField secondDay = new TextField();
pane.add(secondDay, 1, 7);
Label dayThree= new Label("Day Three:");
pane.add(dayThree, 2, 7);
final TextField thirdDay= new TextField();
pane.add(thirdDay, 3, 7);
} else {
}
}
};
moreDays.setOnAction(showMoreLabels);
I´ve tried to create an if-else-statement, when the checkbox is checked, the textfields should be shown and if the statement is false the textfields shouldn´t be visible. But as mentioned it's not working. I hope that somebody can help me.
Thanks already in advance!

Here are a couple of other solutions:
Label dayTwo = new Label("Day Two:");
TextField secondDay = new TextField();
Label dayThree = new Label("Day Three:");
TextField thirdDay = new TextField();
CheckBox moreDays = new CheckBox("Choose more days?");
moreDays.setOnAction(e -> {
if (moreDays.isSelected()) {
pane.add(dayTwo, 0, 7);
pane.add(secondDay, 1, 7);
pane.add(dayThree, 2, 7);
pane.add(thirdDay, 3, 7);
} else {
pane.getChildren().removeAll(dayTwo, secondDay, dayThree, thirdDay);
}
});
or
Label dayTwo = new Label("Day Two:");
pane.add(dayTwo, 0, 7);
TextField secondDay = new TextField();
pane.add(secondDay, 1, 7);
Label dayThree = new Label("Day Three:");
pane.add(dayThree, 2, 7);
TextField thirdDay = new TextField();
pane.add(thirdDay, 3, 7);
bindVisibility(moreDays, dayTwo, secondDay, dayThree, thirdDay);
// ...
private void bindVisibility(CheckBox check, Node... nodes) {
for (Node node : nodes) {
node.visibleProperty().bind(check.selectedProperty());
node.managedProperty().bind(check.selectedProperty());
}
}

Let's change your code a little bit:
Label dayTwo = new Label("Day Two:");
dayTwo.setVisible(false);
pane.add(dayTwo, 0, 7);
TextField secondDay = new TextField();
secondDay.setVisible(false);
pane.add(secondDay, 1, 7);
Label dayThree = new Label("Day Three:");
dayThree.setVisible(false);
pane.add(dayThree, 2, 7);
TextField thirdDay = new TextField();
thirdDay.setVisible(false);
pane.add(thirdDay, 3, 7);
CheckBox moreDays = new CheckBox("Choose more days?");
EventHandler<ActionEvent> showMoreLabels = new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
dayTwo.setVisible(moreDays.isSelected());
secondDay.setVisible(moreDays.isSelected());
dayThree.setVisible(moreDays.isSelected());
thirdDay.setVisible(moreDays.isSelected());
}
};
moreDays.setOnAction(showMoreLabels);
I strongly recommend you finding better names for your labels etc. (e.g. labelDayTwo).

Related

Add padding to the right of the down arrow in a picker in ios renderer

I am adding a down arrow to the xamarin picker. I created a custom iOS renderer for this. I can get the arrow to show up fine, but it is touching the right hand side of the picker. How can I add some padding to the right of the arrow? I have tried the following in my ios renderer.
protected void UpdateBackground(UITextField control)
{
if (control == null) return;
control.Layer.CornerRadius = ElementV2.CornerRadius;
control.Layer.BorderWidth = ElementV2.BorderThickness;
control.Layer.BorderColor = ElementV2.BorderColor.ToCGColor();
var downArrowLabel = new UILabel(new CoreGraphics.CGRect(new CoreGraphics.CGPoint(control.Frame.Size.Width - 20 - 16, 0), new CoreGraphics.CGSize(20, control.Frame.Size.Height)));
downArrowLabel.Font = UIFont.FromName("FontAwesome", 30);
downArrowLabel.Text = "\uf0d7";
downArrowLabel.TextColor = UIColor.Black;
downArrowLabel.TextAlignment = UITextAlignment.Center;
downArrowLabel.ContentMode = UIViewContentMode.ScaleAspectFit;
control.RightView = downArrowLabel;
control.RightViewMode = UITextFieldViewMode.Always;
control.RightView.Bounds = new CoreGraphics.CGRect(0, 0, 20 + 16, control.Frame.Size.Height);
}
I wrote a Picker renderer based on your code and tested it. I found that adding a few spaces after the Text can effectively solve this problem. It looks strange, but it works, like this
downArrowLabel.Text = "\uf0d7 ";

javafx button to read lines from txt to text fields

I am creating a file object that is used in the open and close functions.
For now I am pointing to a specific location and using a fixed name. The file is populated with lines of data.
The button is on the pane, I have a function to openContact which is supposed to read the text file line by line and send the result to the text field setText method, and this function is called when you click on the button.
There are no syntax errors in the editor, but the clicking the button is not populating the fields in the GUI.
Other than that I am not sure what question to ask or what to search for.
I am attaching my code as it is.
Any hints or guidance toward the appropriate questions to ask or thought process would be appreciated.
package programmingassignment1;
import java.awt.Image;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextArea;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.*;
//import javafx.scene.layout.StackPane;
//import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import java.io.*; //input/output
import java.util.Scanner;
//import java.util.*; //scanner, user input
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.image.ImageView;
import javafx.scene.shape.Rectangle;
import javafx.stage.FileChooser;
import javafx.stage.FileChooser.ExtensionFilter;
public class Address extends Application {
String contactFirst,
contactLast,
spouseFirst,
spouseLast,
street,
city,
state,
zip;
TextField tf_contactFirst = new TextField();
TextField tf_contactLast = new TextField();
TextField tf_spouseFirst = new TextField();
TextField tf_spouseLast = new TextField();
TextField tf_street = new TextField();
TextField tf_city = new TextField();
TextField tf_state = new TextField();
TextField tf_zip = new TextField();
TextArea ta_notes = new TextArea();
ExtensionFilter jpgExtension = new ExtensionFilter("JPG", "*.jpg");
ExtensionFilter pngExtension = new ExtensionFilter("PNG", "*.png");
ExtensionFilter allExtension = new ExtensionFilter("ALL", "*.*");
Rectangle imageBox = new Rectangle(10, 0, 10, 20);
FileChooser fc = new FileChooser();
#Override
public void start(Stage primaryStage){
//modify text area and register actions
ta_notes.setWrapText(true);
ta_notes.setEditable(true);
ta_notes.setPrefColumnCount(12);
ta_notes.setPrefRowCount(3);
//Setting an action for the Clear button
Button bt_cancel = new Button("Cancel");
bt_cancel.setOnAction(e -> {
tf_contactFirst.clear();
tf_contactLast.clear();
tf_spouseFirst.clear();
tf_spouseLast.clear();
tf_street.clear();
tf_city.clear();
tf_state.clear();
tf_zip.clear();
ta_notes.setText(null);
});
//Setting an action for the Open Contact button
Button bt_openContact = new Button("Open Contact");
File file = new File("AddressBook.txt");
bt_openContact.setOnAction(e -> {
new EventHandler<ActionEvent>(){
#Override
public void handle(ActionEvent e){
try{openContact(file);}
catch(Exception f){f.getMessage();}
}
};
});
//Setting an action for the Save button
Button bt_save = new Button("Save");
bt_save.setOnAction(
new EventHandler<ActionEvent>(){
#Override
public void handle(ActionEvent e){
try{saveContact(file);}
catch(Exception f){f.getMessage();}
}});
RadioButton rb_male = new RadioButton("Male");
RadioButton rb_female = new RadioButton("Female");
ToggleGroup tgrp = new ToggleGroup();
rb_male.setToggleGroup(tgrp);
rb_female.setToggleGroup(tgrp);
rb_male.setOnAction(e -> {
if(rb_male.isSelected()){int maleContact = 1;}
});
rb_female.setOnAction(e -> {
if(rb_female.isSelected()){int maleContact = 0;}
});
//create combo box and add items as an observable list
String[] x = {"Home Address", "Work Address"};
ComboBox cbo = new ComboBox(FXCollections.observableArrayList(x));
//cbo.setEditable(false);
cbo.setValue("Home Address");
// cbo.setOnAction(e -> {/**____________***/;});
//set imageBox rectangle action
//click in it, choose image, file, its displayed?
//fc is an import or not?
//setOnMouseClicked should work for any node or scene, why not this rect
/*imageBox.setOnMouseClicked((MouseEvent e) -> {
fc.setTitle("Open Image File");
fc.setInitialDirectory(new File("."));
fc.getExtensionFilters().addAll(jpgExtension, pngExtension, allExtension);
fc.setSelectedExtensionFilter(jpgExtension);
File picture = fc.showOpenDialog(primaryStage);
if (picture != null){
rootPane.getChildren().remove(imageBox);
contact.setImageFile(picture.getName());
Image userImage = new Image(picture.getName());
ImageView userView = new ImageView(userImage);
rootPane.getChildren().add(userView);
}
});*/
GridPane rootPane = new GridPane();
rootPane.add(new Label("First Name"), 1, 1);
rootPane.add(tf_contactFirst, 1, 2);
rootPane.add(new Label("Last Name"), 2, 1);
rootPane.add(tf_contactLast, 2, 2);
rootPane.add(new Label("Sex"), 3, 1);
rootPane.add(rb_female, 3, 2);
rootPane.add(rb_male, 3, 3);
rootPane.add(new Label("Spouse's First Name"), 1, 4);
rootPane.add(tf_spouseFirst, 1, 5);
rootPane.add(new Label("Spouse's Last Name"), 2, 4);
rootPane.add(tf_spouseLast, 2, 5);
rootPane.add(cbo, 1, 6);
rootPane.add(new Label("Address Street"), 1, 7);
rootPane.add(tf_street, 1, 8);
rootPane.add(new Label("City"), 1, 9);
rootPane.add(tf_city, 1, 10);
rootPane.add(new Label("State"), 2, 9);
rootPane.add(tf_state, 2, 10);
rootPane.add(new Label("Zip Code"), 3, 9);
rootPane.add(tf_zip, 3, 10);
rootPane.add(imageBox, 4, 1 );
//Label label = new Label();
rootPane.add(new Label("Notes"), 1, 11);
rootPane.add(ta_notes, 1, 12);
rootPane.add(bt_cancel, 2, 13);
rootPane.add(bt_save, 3, 13);
rootPane.add(bt_openContact, 1, 13);
//scene = window (isn't it just easier if someon mentions that?)
Scene scene = new Scene(rootPane, 1000, 500);
primaryStage.setTitle("Address Book");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
public void saveContact(File file) throws FileNotFoundException, Exception{ //declaration
//this code might cause a FileNotFoundException
//if it does it creates an exception object of the above type
try{
//PrintWriter output = new PrintWriter (file);
PrintStream output = new PrintStream(file);
output.println(tf_contactFirst.getText());
output.println(tf_contactLast.getText());
output.println(tf_spouseFirst.getText());
output.println(tf_spouseLast.getText());
output.println(tf_street.getText());
output.println(tf_city.getText());
output.println(tf_state.getText());
output.println(tf_zip.getText());
output.close();
}
//what do do with exception
//here the catch clause with create another exception
//that is passed the result of the getMessage() method from the original exception
catch(FileNotFoundException e){
throw new Exception(e.getMessage());
}
}
//read same text file you save too
public void openContact (File file) throws FileNotFoundException, Exception{
try{
Scanner read = new Scanner(file);
while(read.hasNextLine()){
//how is a blank field recognized, how are two or three
//consecutive tokens handled
//how do I save the imageFileName
tf_contactFirst.setText(read.nextLine());
tf_contactLast.setText(read.nextLine());
//tf_contactGender.setText(read.nextLine());
tf_spouseFirst.setText(read.nextLine());
tf_spouseLast.setText(read.nextLine());
//tf_spouse_gender.setText(read.nextLine());
tf_street.setText(read.nextLine());
tf_city.setText(read.nextLine());
tf_state.setText(read.nextLine());
tf_zip.setText(read.nextLine());
//ta_notes.setText(read.nextLine());
}
}
catch(FileNotFoundException e){
throw new Exception(e.getMessage());
}
}
}
There are several issues with your code that are causing an issue.
First of all, the lambda statement in your setOnAction() method for bt_openContact is incorrect. The openContact() method is never actually being called.
You can correct that with either passing a new EventHandler directly:
bt_openContact.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
try {
openContact(file);
} catch (Exception e) {
e.printStackTrace();
}
}
});
Or using a properly-formatted lamda statement:
bt_openContact.setOnAction(event -> {
try {
openContact(file);
} catch (Exception e) {
e.printStackTrace();
}
});
It appears you were trying to do both. :)
Note also the catch block. Your code is simply calling f.getMessage(), which returns a String. But you don't actually do anything with that String so even if there are errors, you wouldn't see them.
Instead, you should call f.printStackTrace() to actually print any exceptions to the console.
Unrelated Note: Please look into the Java Naming Conventions and stick to them.
Zephir's answer is completely correct.
To answer your question as to hints and guidance:
always, if possible think " why is this here? is there a reason for it? do i need it? " - this will hopefully prevent dead code like : " catch(Exception f){f.getMessage();} "
learn how to use debugers.
It looks like you're trying to figure out how a programming language works, and you probably have some prior experience with other programming languages. Whenever you attempt this, it's a good idea to follow learning trails such as the ones available at https://docs.oracle.com/javase/tutorial/
This is especially important as the more experience in different programming languages you have, the more things start to look the same when in fact they're completely different. Spending 3 hours doing simple tutorials such as these will spare you days of frustration trying to figure out what the hell is going on.
For some reason this looks to me like someone trying to write code directly in notepad or some text editing software. Don't. Use an IDE (netbeans, eclipse, etc.). These come with formatting tools and debuggers which would allow you to find simple issues such as these in less time than it took me to write this answer.

gtk# Vbox not showing up

I'm trying to get 2 VBoxes up in my gtk# application. The problem is, they are not showing up at all. I cannot see the button. What am I doing wrong?
using System;
using Gtk;
using Kassa;
public partial class MainWindow : Gtk.Window
{
VBox left, right;
public MainWindow() : base(Gtk.WindowType.Toplevel)
{
Build();
this.Title = "Kassa";
this.SetSizeRequest(1920, 1080);
//this.Fullscreen();
left = new VBox();
left.HeightRequest = this.HeightRequest;
right = new VBox(true, 0);
right.HeightRequest = this.HeightRequest;
right.WidthRequest = 64 * 4;
Button button = new Button("b");
right.Add(button);
right.PackStart(button, true, false, 0);
button.Show();
this.Add(left);
this.Add(right);
right.Show();
this.ShowAll();
}
protected void OnDeleteEvent(object sender, DeleteEventArgs a)
{
Application.Quit();
a.RetVal = true;
}
}
I have tried every possible combination of Add and ShowAll I can think of.
You should use Window.Add() just once, to add the containing widget (a VBox or similar), and then employ the Box.PackStart() and Box.PackEnd() methods within that container in order to create complex layouts.
Build();
this.Title = "Kassa";
VBox container = new VBox();
left = new VBox();
right = new VBox(true, 0);
Button button = new Button( "b" );
right.Add(button);
right.PackStart( button, true, false, 0 );
container.PackStart( left, true, true, 5 );
container.PackStart( right, true, true, 5 );
this.Add( container );
this.ShowAll();
If you had added the boxes in reverse order, you would see a giant button occupying the whole screen. The explanation is that Window.Add() just adds one item, if you call it twice, then the former is forgotten, and the latter used... exactly the one that had nothing (the former had a button), creating the illusion that nothing was being shown.
Hope this helps.

Slider background in Unity

First I made a picture of my problem:
http://imgur.com/a/D8oOj
You have 3 sliders and they all need a background color. Maybe the 3 labels below need a background color too.
GUI.color = Color.white;
Does not seem to help much. I need this black background for the simulation so i need to make the slider background white...
But GUILayout and GUISkin do not have properties for this, no? I can not find something useful there...
The components i use:
GUI.HorizontalSlider + GUI.Label
Within a GUI Skin, there is a Horizontal Slider property. That property has GUI Style properties of Normal, Hover, Active, and Focused. You should set a background to all 4 of those elements.
Here's an example using programmatically-created GUIStyle (tested with Unity 5.4.2p4). Note that when creating a fresh GUIStyle, you need to assign dimensions, or it might not be visible.
public class MySliderIMGUI : MonoBehaviour
{
private GUIStyle _sliderBackgroundStyle;
private GUIStyle _sliderThumbStyle;
private float _sliderValue = 0f;
private Texture2D _whitePixel;
private Texture2D _blackPixel;
void Start()
{
this._whitePixel = new Texture2D(1, 1, TextureFormat.ARGB32, false);
this._whitePixel.SetPixel(0, 0, Color.white);
this._whitePixel.Apply();
this._blackPixel = new Texture2D(1, 1, TextureFormat.ARGB32, false);
this._blackPixel.SetPixel(0, 0, Color.black);
this._blackPixel.Apply();
this._sliderBackgroundStyle = new GUIStyle();
this._sliderBackgroundStyle.padding = new RectOffset(2, 2, 2, 2);
this._sliderBackgroundStyle.normal.background = this._whitePixel;
this._sliderBackgroundStyle.hover.background = this._whitePixel;
this._sliderBackgroundStyle.active.background = this._whitePixel;
this._sliderBackgroundStyle.focused.background = this._whitePixel;
this._sliderThumbStyle = new GUIStyle();
this._sliderThumbStyle.stretchHeight = true;
this._sliderThumbStyle.fixedWidth = 20f;
this._sliderThumbStyle.normal.background = this._blackPixel;
this._sliderThumbStyle.hover.background = this._blackPixel;
this._sliderThumbStyle.active.background = this._blackPixel;
this._sliderThumbStyle.focused.background = this._blackPixel;
}
void OnGUI()
{
this._sliderValue = GUI.HorizontalSlider(new Rect(100, 100, 200f, 20f), this._sliderValue, 0, 1, this._sliderBackgroundStyle, this._sliderThumbStyle);
}
}

Xamarin.Forms: Exchange view in container

I've created some pages
this.content1 = new DetailPage("ContentPage1");
this.content2 = new DetailPage("ContentPage2");
and I have defined a field
private View detailView;
with the following layout
Content = new StackLayout
{
Padding = new Thickness(0, Device.OnPlatform<int>(20, 0, 0), 0, 0),
Orientation = StackOrientation.Horizontal,
Children = {
buttonContainer,
this.detailView,
},
};
On a button click the detailView should be exchanged
private void Button1_Clicked(object sender, EventArgs e)
{
this.detailView = this.content1.Content;
}
The click event is called, but the view isn't updated. Is this the wrong way to exchange a "subview" in a container? How is this done?
You need to remove the current detailView from the Children collection and then add your new view afterward. Simply swapping the value of detailView will not affect the visual UI.
If I am understanding the context of your code snippets correctly, then this should resolve the problem in your Button1_Clicked handler:
((StackLayout) Content).Children.Remove(this.detailView);
this.detailView = this.content1.Content;
((StackLayout) Content).Children.Add(this.detailView);

Resources