TextField type to Show Button in javafx - javafx-2

I am trying Show a Button on TextField look like Windows 8 Metro theme in javafx.
If TextField is empty button is invisible otherwise button show.
In this stage i'm little close to success. i use this code to make it.
#FXML
private TextField tfMyName;//fx:id="tfMyName"
#FXML
private Button btnClear;//fx:id="btnClear"
#Override
public void initialize(URL url, ResourceBundle rb) {
clearTextFieldByButton(tfMyName, btnClear);
}
public void clearTextFieldByButton(TextField value, Button btn){
btn.setVisible(false);
value.setOnKeyTyped(new EventHandler<KeyEvent>(){
#Override
public void handle(KeyEvent event) {
if ((value.textProperty().get().length() < 0) || (value.textProperty().get().equals(""))) {
btn.setVisible(false);
} else if (value.textProperty().get().length() > -1 || (!value.textProperty().get().equals(""))) {
btn.setVisible(true);
}
}
});
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
tfMyName.clear();
btn.setVisible(false);
tfMyName.requestFocus();
}
});
Using this code by default button is invisible but the button is only visible when i type more then one Characters.
But i need if anything input into the TextField to Button show.
But when i remove the condition under KeyEvent replace by
value.setOnKeyTyped(new EventHandler<KeyEvent>(){
#Override
public void handle(KeyEvent event) {
btn.setVisible(true);
}
});
Then btn show if any character input into the TextField

You may also prefer to use JavaFX binding mechanism:
#Override
public void start( final Stage primaryStage )
{
TextField textfield = new TextField();
Button button = new Button( "my button" );
button.visibleProperty().bind( textfield.textProperty().isEmpty().not() );
final Scene scene = new Scene( new HBox( button, textfield ), 800, 600 );
primaryStage.setScene( scene );
primaryStage.show();
}
The actual problem in your code:
You have attached a listener to field when "OnKeyTyped", at this stage the newly typed text is not appended to the textfield's text value so your if-else condition will not see it. Instead, the correct way should be attaching the listener on "OnKeyReleased".

Add a listener to the textProperty() of the TextField. Check if the value is empty, hide the button else show it. It will be called whenever a character is added or removed from the textfield.
Here is a MCVE, you can just add the listener to the initialize method of the controller.
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class HideButtonOnTextEntered extends Application {
#Override
public void start(Stage stage) {
TextField textField = new TextField();
Button button = new Button("Button");
button.setVisible(false);
VBox root = new VBox(20, textField, button);
root.setAlignment(Pos.CENTER);
Scene scene = new Scene(root, 200, 200);
stage.setScene(scene);
stage.show();
textField.textProperty().addListener((ov, oldValue, newValue) -> {
if (newValue.isEmpty()) {
button.setVisible(false);
} else {
button.setVisible(true);
}
});
}
public static void main(String[] args) {
launch(args);
}
}

Related

use Onclick in extends PagerAdapter

Hi I’m trying to create a horizontal slide where each horizontal page will have a button that will call a Dialog but onClick is not working in extends Pageradapter can anyone tell me what I’m doing wrong?
I gave the name onClickApprove to onClick that I want you to call Dialog. This Dialog is calling an Activity with a Ratingbar to make an assessment.
Thank you.
public class SliderAdapterUsado extends PagerAdapter {
Context context;
LayoutInflater layoutInflater;
BottomSheetDialog dialog;
Button show;
public SliderAdapterUsado(Context context){
this.context = context;
}
public String[] slide_rota ={
"Titulo1",
"Titulo2"
};
public String[] slide_nome={
"Descrção do titulo 1",
"Descrção do titulo 2"
};
#Override
public int getCount(){
return slide_rota.length;
}
#Override
public boolean isViewFromObject(View view, Object object){
return view == (LinearLayout) object;
}
#Override
public Object instantiateItem(ViewGroup container, int position){
layoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.slide_layout_usados, container, false);
TextView slideHeading = view.findViewById(R.id.slide_rota);
TextView slideDescricao = view.findViewById(R.id.slide_nome);
slideHeading.setText(slide_rota[position]);
slideDescricao.setText(slide_nome[position]);
container.addView(view);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object){
container.removeView((LinearLayout)object);
}
public void onClickAvaliar(View view) {
show = view.findViewById(R.id.show);
dialog = new BottomSheetDialog(dialog.getContext());
show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
createDialog();
dialog.show();
}
});
dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
}
private void createDialog(){
View view = layoutInflater.inflate(R.layout.activity_rating, null, false);
Button FeedBack = view.findViewById(R.id.FeedBack);
FeedBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
dialog.setContentView(view);
}
}
Please read the documentation.
Note this in particular (emphasis mine):
To define the click event handler for a button, add the android:onClick attribute to the element in your XML layout. The value for this attribute must be the name of the method you want to call in response to a click event. The Activity hosting the layout must then implement the corresponding method.
The expectation is that the value set on the onClick xml attribute will be a method on the hosting Activity. Yours is in the adapter. That's why it doesn't work.
So either move that method to the hosting activity, or just handle the click event explicitly:
...
TextView slideHeading = view.findViewById(R.id.slide_rota);
TextView slideDescricao = view.findViewById(R.id.slide_nome);
Button slideButton = view.findViewById(R.id.slide_button);
slideButton.setOnClickListener (...)
...

AlertDialog inside checkbox in Android Studio

I am new to Android Studio. I want to create an AlertDialog, which contains a simple TextView, that appears at every lap of time (e.g. 5 min) inside the checkbox, so if the checkbox is clicked, the AlertDialog appears every 5 min. If it's not clicked, then nothing appears. Help me please.
After a bit of experimentation, I was able to create something similar to what I think you want. This is the small project I created, but you can take just the parts of the code that are needed for your project.
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity
{
TextView input;
long startTime = 0;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
final LinearLayout ll = new LinearLayout(this);
setContentView(ll);
CheckBox cb = new CheckBox(getApplicationContext());
cb.setText("Checkbox");
ll.addView(cb);
cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if (isChecked)
{
startTime = System.currentTimeMillis();
timerHandler.postDelayed(timerRunnable, 0);
}
else
{
timerHandler.removeCallbacks(timerRunnable);
}
}
});
}
public void showDialog()
{
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Title");
alert.setMessage("Message");
input = new TextView (this);
alert.setView(input);
input.setText("Text");
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int whichButton)
{
// do stuff when Ok is clicked
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int whichButton)
{
// do stuff when Cancel is clicked
}
});
alert.show();
}
Handler timerHandler = new Handler();
Runnable timerRunnable = new Runnable()
{
#Override
public void run()
{
showDialog();
// Edit the second parameter to whatever time you want in milliseconds
timerHandler.postDelayed(this, 300_000);
}
};
#Override
public void onPause()
{
super.onPause();
timerHandler.removeCallbacks(timerRunnable);
}
}
Hopefully, this helps.

Why does adding JavaFX TableViews to a VBox make other nodes disappear?

EDIT: Forgot the code...
I have an app that let's the user select CSV files for viewing. I'm using JavaFX TableViews to display the data.
For one page, the user can type into a special text box. It's a custom class I made called AutoCompleteTextArea, which extends RichTextFX's StyleClassedTextArea. On other pages, this text box should be hidden. When I have just one TableView, things work fine.
vbox.getChildren().addAll(menuBar, title, subtitle, reqBox, reqTable);
But I need other pages with different TableViews. If I add another TableView to the VBox, my AutoCompleteTextArea goes away!
vbox.getChildren().addAll(menuBar, title, subtitle, reqBox, reqTable, tempTable);
The TableViews do not appear to be overlapping... Any idea why the AutoCompleteTextArea is disappearing? The other weird thing is that if I substitute a regular TextField for the AutoCompleteTextArea, things work fine!
Here's my code. You will need RichTextFX on your build path in order to run it. Use the View Menu to see the problem. The first menu item shows the AutoCompleteTextArea (in the working case). The second menu item shows a different TableView, but this is the broken case - the AutoCompleteTextArea is gone from the first page.
Line 132 is the line in question.
I hope someone is up for the challenge!
More background:
I originally wanted to have just one TableView, and update it's contents based on the user's selection in the View Menu. But I couldn't find a good way to do that, and now here I am again... (see this post: How do I clone a JavaFX TableView?)
package FLOOR;
// --- Imports
import java.util.LinkedList;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
import org.fxmisc.richtext.StyleClassedTextArea;
import javafx.application.Application;
import javafx.beans.property.StringProperty;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.scene.text.TextAlignment;
import javafx.stage.Stage;
// --- Main Class
public class Example extends Application {
// --- All Pages
final Page[] pages = new Page[] {
new Page("Welcome!",
"Welcome Page"),
new Page("Page 1", "Shows Table_1"),
new Page("Page 2", "Shows Table_2"),
};
// --- All Tables
TableView<ObservableList<StringProperty>> reqTable = new TableView<>();
TableView<ObservableList<StringProperty>> tempTable = new TableView<>();
//TextField reqBox = new TextField();
AutoCompleteTextArea reqBox = new AutoCompleteTextArea();
// --- Current Page
final Label title = new Label();
final Label subtitle = new Label();
// --- Main
public static void main(String[] args) { launch(args); }
// --- Start
#Override
public void start(Stage stage) {
// --- Menus
// --- File Menu
// --- Import Submenu
Menu menuFile = new Menu("File");
Menu importMenu = new Menu("Import");
MenuItem reqOption = new MenuItem("Requirements");
MenuItem tempOption = new MenuItem("Templates");
importMenu.getItems().addAll(reqOption, tempOption);
//Import Requirements
reqOption.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
//TODO
}
});
//Import Templates
tempOption.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
//TODO
}
});
//Export
MenuItem export = new MenuItem("Export");
export.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent t) {
//TODO
}
});
//Exit
MenuItem exit = new MenuItem("Exit");
exit.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent t) {
System.exit(0);
}
});
menuFile.getItems().addAll(importMenu, export, new SeparatorMenuItem(), exit);
// --- View Menu
Menu menuView = new Menu("View");
//Page1
MenuItem viewRequirements = new MenuItem("Requirements");
viewRequirements.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent t) {
getPage1();
}
});
//Page2
MenuItem viewTemplates = new MenuItem("Templates");
viewTemplates.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent t) {
getPage2();
}
});
menuView.getItems().addAll(viewRequirements, viewTemplates);
// --- Menu Bar
MenuBar menuBar = new MenuBar();
menuBar.getMenus().addAll(menuFile, menuView);
// --- VBox
final VBox vbox = new VBox();
vbox.setAlignment(Pos.TOP_CENTER);
vbox.setSpacing(10);
reqTable.setMinHeight(300);
tempTable.setMinHeight(300);
reqTable.translateYProperty().set(30);
tempTable.translateYProperty().set(-275);
reqTable.setVisible(false);
tempTable.setVisible(false);
reqBox.setVisible(false);
// --- Welcome Page
title.setFont(new Font("Arial", 24));
title.translateYProperty().set(10);
title.setText(pages[0].title);
subtitle.setText(pages[0].subtitle);
subtitle.setMinHeight(30);
subtitle.setTextAlignment(TextAlignment.CENTER);
// --- Show FLOOR
vbox.getChildren().addAll(menuBar, title, subtitle, reqBox, reqTable);
//vbox.getChildren().addAll(menuBar, title, subtitle, reqBox, reqTable, tempTable);
Scene scene = new Scene(vbox, 900, 500);
stage.setScene(scene);
stage.setTitle("FLOOR");
stage.show();
}
// --- Methods
// Page Getters
private void getPage1() {
title.setFont(new Font("Arial", 24));
title.translateYProperty().set(10);
title.setText(pages[1].title);
subtitle.setText(pages[1].subtitle);
subtitle.setMinHeight(20);
reqBox.setVisible(true);
reqTable.setVisible(true);
tempTable.setVisible(false);
}
private void getPage2() {
title.setFont(new Font("Arial", 24));
title.translateYProperty().set(10);
title.setText(pages[2].title);
subtitle.setText(pages[2].subtitle);
subtitle.setMinHeight(20);
reqBox.setVisible(false);
reqTable.setVisible(false);
tempTable.setVisible(true);
}
// --- Classes
// Page
private class Page {
public String title;
public String subtitle;
public Page(String title, String subtitle) {
this.title = title;
this.subtitle = subtitle;
}
}
// AutoCompleteTextArea
public class AutoCompleteTextArea extends StyleClassedTextArea {
public final SortedSet<String> entries;
public ContextMenu entriesPopup;
public AutoCompleteTextArea() {
super();
entries = new TreeSet<>();
entriesPopup = new ContextMenu();
}
public SortedSet<String> getEntries() { return entries; }
public void populatePopup(List<String> searchResult) {
List<CustomMenuItem> menuItems = new LinkedList<>();
int maxEntries = 20;
int count = Math.min(searchResult.size(), maxEntries);
for (int i = 0; i < count; i++) {
final String result = searchResult.get(i);
Label entryLabel = new Label(result);
CustomMenuItem item = new CustomMenuItem(entryLabel, true);
menuItems.add(item);
}
entriesPopup.getItems().clear();
entriesPopup.getItems().addAll(menuItems);
}
}
}

JavaFX -- after modal dialog cursor left in incorrect state and cannot be corrected

I have a modal dialog that I pop up, which contains text boxes. If the user has the mouse over the text box (so the TEXT cursor shows) and then hits Enter to close the dialog, the cursor gets left in the TEXT state. So far I have found no way programmatically to change it back to the DEFAULT state. If I try some other cursor on the main scene (like HAND or MOVE) it works. But DEFAULT does not.
I'm using JavaFx / JDK 1.7 that was "fresh" when I downloaded within the last couple of months. I'm on Windows 8.1.
I've searched the web a fair bit and haven't found any mention of it. Is this a known bug? Can anybody suggest a workaround or explain what is going on?
Code sample follows. Simply click on the text edit in the dialog, keep the mouse over the textbox so the cursor is TEXT, and hit Enter.
package jfxtest;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Cursor;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Modality;
import javafx.stage.Stage;
public class Jfxtest extends Application {
public static void main(String[] args) {
launch(args);
}
#Override public void start(final Stage primaryStage) {
Button btn = new Button();
btn.setText("Open Dialog");
btn.setOnAction(
new EventHandler<ActionEvent>() {
#Override public void handle(ActionEvent event) {
final Stage dialog = new Stage();
dialog.initModality(Modality.APPLICATION_MODAL);
dialog.initOwner(primaryStage);
final TextField txt = new TextField("Hit Enter while I have focus and the mouse is over me!");
txt.setMinWidth(280);
Button btnOk = new Button("OK");
btnOk.setDefaultButton(true);
btnOk.setOnAction(
new EventHandler<ActionEvent>() {
#Override public void handle(ActionEvent event) {
// these don't work
txt.setCursor(Cursor.DEFAULT);
dialog.getScene().setCursor(Cursor.DEFAULT);
primaryStage.getScene().setCursor(Cursor.DEFAULT);
dialog.close();
// and these don't work
txt.setCursor(Cursor.DEFAULT);
dialog.getScene().setCursor(Cursor.DEFAULT);
primaryStage.getScene().setCursor(Cursor.DEFAULT);
}
} );
VBox dialogVbox = new VBox(20);
dialogVbox.getChildren().add(txt);
dialogVbox.getChildren().add(btnOk);
Scene dialogScene = new Scene(dialogVbox, 300, 200);
dialog.setScene(dialogScene);
dialog.showAndWait();
// and these doesn't work
dialogScene.setCursor(Cursor.DEFAULT);
primaryStage.getScene().setCursor(Cursor.DEFAULT);
// but this works as expected (!), although it doesn't solve my problem
// primaryStage.getScene().setCursor(Cursor.HAND);
}
} );
VBox vbox = new VBox(20);
vbox.getChildren().add(btn);
Scene scene = new Scene (vbox, 400, 300);
primaryStage.setScene(scene);
primaryStage.show();
}
}

JavaFX2: MODAL capability to a context menu

Is there a way to add MODAL capability to a context menu?
My code is below:
package snippet;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.ColorPicker;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Label;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
public class ContextMenuSample extends Application
{
public static void main(String[] args)
{
launch(args);
}
#Override
public void start(Stage stage)
{
stage.setTitle("ContextMenuSample");
Scene scene = new Scene(new Group(), 450, 250);
Label toLabel = new Label("To: ");
TextField notification = new TextField();
final ContextMenu contextMenu = new ContextMenu();
contextMenu.setAutoHide(false);
contextMenu.setOnShowing(new EventHandler<WindowEvent>()
{
public void handle(WindowEvent e)
{
System.out.println("showing the context menu");
}
});
contextMenu.setOnShown(new EventHandler<WindowEvent>()
{
public void handle(WindowEvent e)
{
System.out.println("context menu has been shown");
}
});
MenuItem closeItem = new MenuItem("Close");
closeItem.setOnAction(new EventHandler<ActionEvent>()
{
public void handle(ActionEvent e)
{
contextMenu.hide();
}
});
MenuItem colorItem = new MenuItem("Choose", new ColorPicker());
colorItem.setOnAction(new EventHandler<ActionEvent>()
{
public void handle(ActionEvent e)
{
System.out.println("Preferences");
}
});
GridPane contextGridPane = new GridPane();
Pane pane = new Pane();
pane.getChildren().add(contextGridPane);
contextMenu.getItems().addAll(colorItem, deleteItem// , subsystem1,
// radioItem
);
toLabel.setContextMenu(contextMenu);
GridPane grid = new GridPane();
grid.setVgap(4);
grid.setHgap(10);
grid.setPadding(new Insets(5, 5, 5, 5));
grid.add(toLabel, 0, 0);
grid.add(notification, 1, 0);
grid.add(new ColorPicker(), 2, 0);
Group root = (Group) scene.getRoot();
root.getChildren().add(grid);
stage.setScene(scene);
stage.show();
}
}
When the user clicks on the label "To", a context menu appears. I wish to have modal capability for this context menu such that the user is not able to do anything else on the application unless some operation is performed on the context menu. Also, when the context menu is active, the user should not be able to click anywhere else on the application.
Regards,
The easiest solution would be to call another Stage and set its modality with initModality before you show the stage. You probably want to use Modality.APPLICATION_MODEL as far as I understood you.
Here is a small example derived from yours (btw your code was not even runnable, it had errors)
public class ContextMenuSample extends Application
{
public static void main(String[] args)
{
launch(args);
}
#Override
public void start(final Stage stageOne)
{
final Stage stageTwo = new Stage();
stageTwo.initModality(Modality.APPLICATION_MODAL);
final Pane layoutOne = new HBox(10);
Pane layoutTwo = new HBox(10);
Label labelOne = new Label("click");
Label labelTwo = new Label("other click");
labelOne.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
stageTwo.show();
}
});
labelTwo.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
stageTwo.close();
}
});
Scene sceneOne = new Scene(layoutOne);
Scene sceneTwo = new Scene(layoutTwo);
layoutOne.getChildren().add(labelOne);
layoutTwo.getChildren().add(labelTwo);
stageOne.setScene(sceneOne);
stageTwo.setScene(sceneTwo);
stageOne.show();
}
}

Resources