javafx button.onclick() not working - javafx

i am having a problem when i click on the button it doesn t work.
actually for the moment i am just asking that the button execute a system.out.println() just for the test. the name of the button is btndetailUser
listRechercheUser.setCellFactory(new Callback<ListView<User>, ListCell<User>>() {
#Override
public ListCell<User> call(ListView<User> p) {
ListCell<User> cell;
cell = new ListCell<User>() {
#Override
protected void updateItem(User user, boolean bln) {
super.updateItem(user, bln);
if (user != null) {
ImageView img;
String mm=user.getPath().trim();
if (mm.equals("fusee.png")){
img = new ImageView(new Image("mto/cr/images/"+mm));}
else{
img = new ImageView(new Image("mto/cr/images/mains-fonds.png"));
}
VBox vb = new VBox(10);
HBox hb = new HBox(20);
VBox vb1 = new VBox(20);
VBox vb3= new VBox(20);
vb1.getChildren().add(new Label(" "));
hb.setStyle("-fx-border-color: #C8C8C8 ;");
vb.setAlignment(Pos.CENTER);
VBox vb2 = new VBox(30);
vb.setAlignment(Pos.CENTER);
vb2.setAlignment(Pos.BASELINE_LEFT);
vb3.setAlignment(Pos.CENTER_RIGHT);
Label id = new Label(user.getId()+"id firas:");
Label username = new Label(user.getUsername()+" username firas:");
Label nom = new Label(user.getNom()+"nom firas:");
Label prenom = new Label(user.getPrenom()+"prenom firas:");
Button btndetailUser = new Button();
btndetailUser.setId("btndetailUser");
btndetailUser.setText("btndetailUser "+user.getId());
Image imageAccesProjet = new Image("mto/cr/images/enter.png");
ImageView enterIV= new ImageView(imageAccesProjet);
enterIV.setFitHeight(10);
enterIV.setFitWidth(10);
btndetailUser.setGraphic(enterIV);
btndetailUser.getStyleClass().add("buttonLogin");
System.out.println(btndetailUser.getText());
btndetailUser.setOnMouseClicked(
(MouseEvent event2) ->
System.out.println("firas"));
btndetailUser.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
System.out.println(".handle()");
}
});
vb.getChildren().addAll(new Label(" "), img, new Label(" "),username);
vb2.getChildren().addAll(nom, prenom);
vb3.getChildren().addAll(btndetailUser);
hb.getChildren().addAll(vb1, vb, vb2,vb3);
setGraphic(hb);
}
}
};
return cell;
}
});

try something like,
btndetailUser.setOnAction(e -> {
System.out.println("freetext")
});

Related

refresh label during a foreach loop

I'm asking for your help.
I'm developing an application in JavaFX who "scan" Mp3 files to get ID3tag.
Here is my problem. I did a foreach loop of a list for every .mp3 found but I'd like to increment a label which inform the progression of the list.
Here is my code
private ArrayList checkMp3File(ArrayList<String> lsMp3file, String sDir) throws UnsupportedTagException, InvalidDataException, IOException
{
this.currentData = 1;
int size = lsMp3file.size();
ArrayList<DataSong> lsds = new ArrayList<>();
for(String mp3file : lsMp3file)
{
this.labelUpdate.setText(this.current++ + " of " + " size");
DataSong ds = new DataSong();
Mp3File mp3 = new Mp3File(mp3file);
ds.setLenghtOfMp3inSec(mp3.getLengthInSeconds());
ds.setBitRateOfMp3(mp3.getBitrate());
ds.setSampleRate(mp3.getSampleRate());
ds.setVbrOrCbr(mp3.isVbr());
}
Actually, when the loop progress my window interface is completely freeze.
And only when the loop is finished, the label updated.
Someone can explain why ?
I already thank you for your answers.
EDIT :
Here is my fully code
public class LaunchOption extends Pane {
private final HBox launchAndSend = new HBox();
private final HBox browseAndField = new HBox();
private final HBox jsonAndAdvance = new HBox();
private ArrayList<DataSong> lsWithData = new ArrayList<>();
private String sendJson;
private File selectedDirectory;
private User user;
private int currentData;
private final ProgressIndicator pi = new ProgressIndicator(0);
private final VBox containerElement = new VBox();
private final TextArea displayJson = new TextArea();
private final TextField pathDir = new TextField();
private final TextField nbrOfData = new TextField();
private final Button btnScan = new Button();
private final Button btnSend = new Button();
private final Button btnCheckJson = new Button();
private final Button btnDirectoryBrowser = new Button();
private final Label nbMp3 = new Label();
public Label listAdvance = new Label();
private final Stage home;
public LaunchOption(Stage home){
this.home = home;
configureBtnCheckJson();
configureBtnScan();
configureBtnSend();
configureLabelMp3();
configureBtnDirectoryBrowser();
configureTextAreaDisplayJson();
configureTextFieldPathDir();
configureTextFieldNbDataMp3();
configureHBoxlaunchSend();
configureHBoxBrowseAndField();
configureHBoxJsonAndAdvance();
configureContainer();
this.getChildren().addAll(containerElement,launchAndSend);
}
private void configureLabelMp3()
{
nbMp3.setText("MP3");
}
private void configureBtnScan(){
btnScan.setText("Scan");
btnScan.setOnAction(event->{
ArrayList<String> Mp3FileData;
Mp3FileData = mapFilesMp3(selectedDirectory.getAbsolutePath());
System.out.println("ListSize = " + Mp3FileData.size());
nbrOfData.setText(String.valueOf(Mp3FileData.size()));
try {
lsWithData = checkMp3File(Mp3FileData, selectedDirectory.getAbsolutePath());
} catch (UnsupportedTagException ex) {
Logger.getLogger(MusiScanMp3agic.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidDataException ex) {
Logger.getLogger(MusiScanMp3agic.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(MusiScanMp3agic.class.getName()).log(Level.SEVERE, null, ex);
}
pi.setProgress(1);
});
}
private void configureBtnDirectoryBrowser(){
btnDirectoryBrowser.setText("Browse ...");
btnDirectoryBrowser.getStyleClass().add("round-red");
btnDirectoryBrowser.setOnAction(event-> {
DirectoryChooser dc = new DirectoryChooser();
selectedDirectory = dc.showDialog(home);
pi.setProgress(0.35);
if(selectedDirectory == null)
{
pathDir.setText("No directory selected");
}
else
{
pathDir.setText(selectedDirectory.getAbsolutePath());
String Text = pathDir.getText();
System.out.println(Text.toString());
}
});
}
private static String regexMp3()
{
return "^.*\\.(mp3)$";
}
private ArrayList mapFilesMp3(String sDir){
ArrayList<String> ls = new ArrayList<>();
printFnames(sDir,ls);
return ls;
}
private static void printFnames(String sDir, ArrayList<String> ls)
{
File[] faFiles = new File(sDir).listFiles();
for(File file : faFiles)
{
if(file.getName().matches(regexMp3()))
{
// System.out.println(file.getAbsolutePath());
ls.add(file.getAbsolutePath());
}
if(file.isDirectory())
{
printFnames(file.getAbsolutePath(), ls);
}
}
}
private ArrayList checkMp3File(ArrayList<String> lsMp3file, String sDir) throws UnsupportedTagException, InvalidDataException, IOException
{
this.currentData = 1;
int size = lsMp3file.size();
ArrayList<DataSong> lsds = new ArrayList<>();
for(String mp3file : lsMp3file)
{
System.out.println(this.currentData++);
DataSong ds = new DataSong();
Mp3File mp3 = new Mp3File(mp3file);
ds.setLenghtOfMp3inSec(mp3.getLengthInSeconds());
ds.setBitRateOfMp3(mp3.getBitrate());
ds.setSampleRate(mp3.getSampleRate());
ds.setVbrOrCbr(mp3.isVbr());
if(mp3 != null){
ds.setAbsoluteLocation(mp3.getFilename());
ds.setLocation(removeSDir(mp3.getFilename(), sDir));
if(mp3.hasId3v2Tag())
{
ID3v2 id3v2Tag = mp3.getId3v2Tag();
if(!(id3v2Tag.getArtist() == null))
{
ds.setArtist(id3v2Tag.getAlbumArtist());
}
if(!(id3v2Tag.getAlbum() == null))
{
ds.setAlbum((id3v2Tag.getAlbum()));
}
if(!(id3v2Tag.getTitle() == null))
{
ds.setTitle(id3v2Tag.getTitle());
}
if(!(id3v2Tag.getTrack() == null))
{
ds.setTrackOnAlbum(id3v2Tag.getTrack());
}
if(!(id3v2Tag.getYear() == null) && !(id3v2Tag.getYear().isEmpty()))
{
ds.setYearReleased(id3v2Tag.getYear());
}
if(!(id3v2Tag.getGenreDescription() == null))
{
ds.setGenre(id3v2Tag.getGenreDescription());
}
if(!(id3v2Tag.getComposer() == null))
{
ds.setComposer(id3v2Tag.getComposer());
}
if(!(id3v2Tag.getPublisher() == null))
{
ds.setPublisher(id3v2Tag.getPublisher());
}
if(!(id3v2Tag.getOriginalArtist() == null))
{
ds.setOriginArtist(id3v2Tag.getOriginalArtist());
}
if(!(id3v2Tag.getAlbumArtist() == null))
{
ds.setAlbumArtString(id3v2Tag.getAlbumArtist());
}
if(!(id3v2Tag.getCopyright() == null))
{
ds.setCopyright(id3v2Tag.getCopyright());
}
if(!(id3v2Tag.getUrl() == null))
{
ds.setUrl(id3v2Tag.getUrl());
}
}
}
lsds.add(ds);
}
return lsds;
}
I presume that what I should do is to make my checkMp3File method into a Task method which will do a background thread ?
There is not enough code to be sure but I think you are probably calling your method on the JavaFX application thread which then blocks your UI.
You should read the documentation about concurrency in JavaFX.
https://docs.oracle.com/javase/8/javafx/interoperability-tutorial/concurrency.htm

How can the text of the label be shown?

As you can see in the picture, the label in the third box, next to the ComboBox, has the text '...' instead of 'fase'.
I have previously attempted to increase the size of the HBox in which it resides, increasing spacing, but to no avail. Any suggestions?
public void start(Stage primaryStage) {
RadioButtonCustom inhoud = new RadioButtonCustom();
Fieldset fs = new Fieldset("eerste", inhoud);
RadioButtonCustom inhoud2 = new RadioButtonCustom();
Fieldset fs2 = new Fieldset("tweede", inhoud2);
//error
HBox hb = new HBox();
hb.minWidth(200);
Label fase = new Label("fase");
fase.setText("Fase");
fase.minWidth(500);
fase.getStyleClass().add("bordered-titled-title");
StackPane.setAlignment(fase, Pos.CENTER);
ComboBox<Integer> cb = new ComboBox<>();
hb.setSpacing(40);
for (Integer i : array) {
cb.getItems().add(i);
}
hb.getChildren().addAll(fase,cb);
Fieldset fs3 = new Fieldset("fase",hb);
// einde error
VBox vb = new VBox();
vb.getChildren().addAll(fs, fs2,fs3);
vb.setSpacing(20);
Button btn = new Button();
btn.setText("Say 'Hello World'");
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
System.out.println("Hello World!");
}
});
BorderPane root = new BorderPane();
root.getChildren().add(vb);
Scene scene = new Scene(root, 500, 500);
scene.getStylesheets().add("/lissa/stijl.css");
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}

How to disable Button when TextField is empty?

In the following code I have a TextField and a Button. I need to disable the Button when ever the TextField is empty, so that I can avoid entering empty values to the database. How can I make the button disabled ?
private VBox addVBox() {
VBox vb1 = new VBox();
vb1.setPadding(new Insets(15, 20, 25, 20));
vb1.setSpacing(15);
vb1.setStyle("-fx-background-color: #333333;");
final Label label = new Label("Staff Details");
label.setFont(Font.font("Arial", FontWeight.BOLD, 20));
label.setTextFill(Color.WHITE);
TableColumn sub = new TableColumn("Staff Name");
sub.setMinWidth(400);
sub.setCellValueFactory(
new PropertyValueFactory<Staff, String>("subName"));
table.setItems(data);
table.getColumns().addAll(sub);
addSubName = new TextField();
addSubName.setPromptText("Staff Name");
addSubName.setPrefSize(200, 30);
final Button b2 = new Button("Add");
b2.setFont(Font.font("Calibri", FontWeight.BOLD, 17));
b2.setPrefSize(70, 30);
b2.setStyle(" -fx-base: #0066ff;");
b2.setTextFill(Color.BLACK);
b2.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent e) {
msg = addSubName.getText();
try {
enterStaff();
} catch ( ClassNotFoundException | SQLException ex) {
Logger.getLogger(AddStaff.class.getName()).log(Level.SEVERE, null, ex);
}
data.add(new Staff(addSubName.getText()));
addSubName.clear();
}
});
hb.getChildren().addAll(addSubName, b2);
hb.setSpacing(5);
vb1.getChildren().addAll(label, table, hb);
return vb1;
}
Similar to Uluk's answer, but using the Bindings fluent API:
btn.disableProperty().bind(
Bindings.isEmpty(textField1.textProperty())
.and(Bindings.isEmpty(textField2.textProperty()))
.and(Bindings.isEmpty(textField3.textProperty()))
);
Also note that, this new overloaded method of Bindings is added in JavaFX-8 and not avaliable in JavaFX-2.
The other way can be using bindings:
final TextField textField1 = new TextField();
final TextField textField2 = new TextField();
final TextField textField3 = new TextField();
BooleanBinding bb = new BooleanBinding() {
{
super.bind(textField1.textProperty(),
textField2.textProperty(),
textField3.textProperty());
}
#Override
protected boolean computeValue() {
return (textField1.getText().isEmpty()
&& textField2.getText().isEmpty()
&& textField3.getText().isEmpty());
}
};
Button btn = new Button("Button");
btn.disableProperty().bind(bb);
VBox vBox = new VBox();
vBox.getChildren().addAll(textField1, textField2, textField3, btn);
use textProperty() Listener for TextField
try this...
Button b1 = new Button("DELETE");
b1.setFont(Font.font("Calibri", FontWeight.BOLD, 17));
b1.setPrefSize(100, 30);
b1.setStyle(" -fx-base: #ffffff;");
b1.setTextFill(Color.BLACK);
b1.setDisable(true); // Initally text box was empty so button was disable
txt1.textProperty().addListener(new ChangeListener<String>() {
#Override
public void changed(ObservableValue<? extends String> ov, String t, String t1) {
//System.out.println(t+"====="+t1);
if(t1.equals(""))
b1.setDisable(true);
else
b1.setDisable(false);
}
});

Display Label and Progressbar into combo box

I have this code which is used to display text into combo box.
ProgressBar pb1 = new ProgressBar(0.6);
ProgressIndicator pi1 = new ProgressIndicator(0.6);
VBox vb1 = new VBox();
vb1.getChildren().addAll(new Label("Progressbar 1"), pi1);
ProgressBar pb2 = new ProgressBar(0.6);
ProgressIndicator pi2 = new ProgressIndicator(0.6);
VBox vb2 = new VBox();
vb2.getChildren().addAll(new Label("Progressbar 2"), pi2);
ProgressBar pb3 = new ProgressBar(0.6);
ProgressIndicator pi3 = new ProgressIndicator(0.6);
VBox vb3 = new VBox();
vb3.getChildren().addAll(new Label("Progressbar 3"), pi3);
TextChooser textChooser = new TextChooser(
vb1, vb2, vb3
);
textChooser.setStyle("-fx-font: 10px \"Verdana\";");
VBox layout = new VBox(textChooser);
layout.setPadding(new Insets(22, 22, 22, 22));
public static class TextChooser extends StackPane {
private Label label = new Label();
private ComboBox<String> combo = new ComboBox<>();
public TextChooser(String... options) {
StackPane.setAlignment(label, Pos.CENTER_LEFT);
StackPane.setAlignment(combo, Pos.CENTER_LEFT);
label.textProperty().bind(
combo.getSelectionModel().selectedItemProperty()
);
label.visibleProperty().bind(
combo.visibleProperty().not()
);
label.setPadding(new Insets(0, 0, 0, 10));
combo.getItems().setAll(options);
combo.getSelectionModel().select(0);
combo.setVisible(false);
label.setOnMouseEntered(event -> combo.setVisible(true));
combo.showingProperty().addListener(observable -> {
if (!combo.isShowing()) {
combo.setVisible(false);
}
});
combo.setOnMouseExited(event -> {
if (!combo.isShowing()) {
combo.setVisible(false);
}
});
getChildren().setAll(label, combo);
}
}
In my case I cannot insert VBox into the combo box. Any idea how I can fix this?
The biggest problem with your code is trying to construct a TextChooser using VBoxes when the formal parameters are Strings. Change your constructor to public TextChooser(VBox... options) and the ComboBox declaration to private ComboBox<VBox> combo = new ComboBox<>();.
Now you will be able to add the items to the combo box, and if it works, you are done. If you experience the issue with adding Nodes to a ComboBox, you may want to add more code. The problem and solution are described in the Javadoc for ComboBox: http://docs.oracle.com/javafx/2/api/javafx/scene/control/ComboBox.html. To get around the fact that the item you select will be removed from the combo box, you need to change this code (taken from the javadoc):
combo.setCellFactory(new Callback<ListView<VBox>, ListCell<VBox>>() {
#Override public ListCell<VBox> call(ListView<VBox> p) {
return new ListCell<VBox>() {
#Override protected void updateItem(VBox item, boolean empty) {
super.updateItem(item, empty);
if (item == null || empty) {
setGraphic(null);
} else {
setGraphic(item);
}
}
};
}
});
after the line getItems().setAll(options);.
This is what your full example code would turn into:
ProgressBar pb1 = new ProgressBar(0.6);
ProgressIndicator pi1 = new ProgressIndicator(0.6);
VBox vb1 = new VBox();
vb1.getChildren().addAll(new Label("Progressbar 1"), pi1);
ProgressBar pb2 = new ProgressBar(0.6);
ProgressIndicator pi2 = new ProgressIndicator(0.6);
VBox vb2 = new VBox();
vb2.getChildren().addAll(new Label("Progressbar 2"), pi2);
ProgressBar pb3 = new ProgressBar(0.6);
ProgressIndicator pi3 = new ProgressIndicator(0.6);
VBox vb3 = new VBox();
vb3.getChildren().addAll(new Label("Progressbar 3"), pi3);
TextChooser textChooser = new TextChooser(
vb1, vb2, vb3
);
textChooser.setStyle("-fx-font: 10px \"Verdana\";");
VBox layout = new VBox(textChooser);
layout.setPadding(new Insets(22, 22, 22, 22));
public static class TextChooser extends StackPane {
private Label label = new Label();
private ComboBox<VBox> combo = new ComboBox<>();
public TextChooser(VBox... options) {
StackPane.setAlignment(label, Pos.CENTER_LEFT);
StackPane.setAlignment(combo, Pos.CENTER_LEFT);
label.textProperty().bind(
combo.getSelectionModel().selectedItemProperty()
);
label.visibleProperty().bind(
combo.visibleProperty().not()
);
label.setPadding(new Insets(0, 0, 0, 10));
combo.getItems().setAll(options);
// vvvv Begin Optional Part vvvv
combo.setCellFactory(new Callback<ListView<VBox>, ListCell<VBox>>() {
#Override public ListCell<VBox> call(ListView<VBox> p) {
return new ListCell<VBox>() {
#Override protected void updateItem(VBox item, boolean empty) {
super.updateItem(item, empty);
if (item == null || empty) {
setGraphic(null);
} else {
setGraphic(item);
}
}
};
}
});
// ^^^^ End Optional Part ^^^^
combo.getSelectionModel().select(0);
combo.setVisible(false);
label.setOnMouseEntered(event -> combo.setVisible(true));
combo.showingProperty().addListener(observable -> {
if (!combo.isShowing()) {
combo.setVisible(false);
}
});
combo.setOnMouseExited(event -> {
if (!combo.isShowing()) {
combo.setVisible(false);
}
});
getChildren().setAll(label, combo);
}
}

FX 2.x : How do I remove SplitPane?

I can add SplitPane in a XYChart by clicking the "Add Pane" button, and it works fine.
Now I would like to remove SplitPane by clicking the "Remove pane" button.
Here is full code
public class SplitPaneFxTest extends Application {
SplitPane splitPane = new SplitPane();
double percSplit = 0.50;
int idxSplit = 0;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(SplitPaneFxTest.class, args);
}
#Override
public void start(Stage primaryStage) {
primaryStage.setTitle("SplitPane Test");
Group root = new Group();
Scene scene = new Scene(root, 800, 650, Color.WHITE);
//CREATE THE SPLITPANE
splitPane.setPrefSize(scene.getWidth(), scene.getHeight());
splitPane.setOrientation(Orientation.VERTICAL);
//ADD LAYOUTS AND ASSIGN CONTAINED CONTROLS
BorderPane upperPane = new BorderPane();
HBox hbox = new HBox();
Button button1 = new Button("Add Pane");
hbox.getChildren().addAll(button1);
upperPane.setTop(hbox);
Button button2 = new Button("Remove Pane");
hbox.getChildren().addAll(button2);
upperPane.setTop(hbox);
BorderPane lowerPane = new BorderPane();
splitPane.getItems().addAll(upperPane);
splitPane.setDividerPosition(idxSplit, 0.70);
idxSplit++;
splitPane.getItems().addAll(lowerPane);
idxSplit++;
root.getChildren().add(splitPane);
primaryStage.setScene(scene);
primaryStage.show();
button1.setOnAction(new EventHandler<ActionEvent>() {
#Override public void handle(ActionEvent e) {
BorderPane myborderpane = new BorderPane();
splitPane.getItems().addAll(myborderpane);
ObservableList<SplitPane.Divider> splitDiv = splitPane.getDividers();
System.out.println("splitDiv.size() "+splitDiv.size());
percSplit = 1/(double)(splitDiv.size()+1);
for (int i = 0; i< splitDiv.size(); i++) {
System.out.println("i "+i+" percSplit "+percSplit);
splitPane.setDividerPosition(i, percSplit);
percSplit += 1/(double)(splitDiv.size()+1);
}
}
});
}
}
Any help really appreciated.
You can store a list of inner panes and remove them based on this list:
final List<Pane> panes = new ArrayList<Pane>();
button1.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent e) {
BorderPane myborderpane = new BorderPane();
//adding
panes.add(myborderpane);
splitPane.getItems().addAll(myborderpane);
ObservableList<SplitPane.Divider> splitDiv = splitPane.getDividers();
System.out.println("splitDiv.size() " + splitDiv.size());
percSplit = 1 / (double) (splitDiv.size() + 1);
for (int i = 0; i < splitDiv.size(); i++) {
System.out.println("i " + i + " percSplit " + percSplit);
splitPane.setDividerPosition(i, percSplit);
percSplit += 1 / (double) (splitDiv.size() + 1);
}
}
});
button2.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent t) {
if (panes.size() > 0) {
// removing from both list and splitPane childs
Pane toDelete = panes.remove(0);
splitPane.getItems().remove(toDelete);
}
}
});
Also you can remove panes directly from ScrollPane.getChildren() but it can involve tricky and unreliable code to determine which pane to remove.

Resources