how can I bind gridview column count to window in JavaFX - javafx

I have a dynamic gridview. I created a custom design for GridView items. But since the number of columns is static, the blank space increases when the window increases(sorry my english is bad)
default window size:
and how it looks when the screen is enlarged:
public void initgrit( ){
noBarcodes = new ArrayList<>(products());
int col = 0;
int row =0;
for (ProductNoBarcode noBarcode: noBarcodes){
try {
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(getClass().getResource("/fxml/testView.fxml"));
VBox vBox = fxmlLoader.load();
testView testView1 = fxmlLoader.getController();
testView1.setInfo(noBarcode);
if (col == 3){
col=0;
++row;
}
gridPane.add(vBox,col++,row);
GridPane.setMargin(vBox,new Insets(10,10,10,10));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}

Related

JavaFX - creating a new window on button clicked(using Scene Builder) [duplicate]

Looking at this code they show a way to display a new window after a login. When username and password are correct it opens new dialog. I want a button click to open new dialog, without checking for username and password.
If you just want a button to open up a new window, then something like this works:
btnOpenNewWindow.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
Parent root;
try {
root = FXMLLoader.load(getClass().getClassLoader().getResource("path/to/other/view.fxml"), resources);
Stage stage = new Stage();
stage.setTitle("My New Stage Title");
stage.setScene(new Scene(root, 450, 450));
stage.show();
// Hide this current window (if this is what you want)
((Node)(event.getSource())).getScene().getWindow().hide();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
I use the following method in my JavaFX applications.
newWindowButton.setOnMouseClicked((event) -> {
try {
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(getClass().getResource("NewWindow.fxml"));
/*
* if "fx:controller" is not set in fxml
* fxmlLoader.setController(NewWindowController);
*/
Scene scene = new Scene(fxmlLoader.load(), 600, 400);
Stage stage = new Stage();
stage.setTitle("New Window");
stage.setScene(scene);
stage.show();
} catch (IOException e) {
Logger logger = Logger.getLogger(getClass().getName());
logger.log(Level.SEVERE, "Failed to create new Window.", e);
}
});
The code below worked for me I used part of the code above inside the button class.
public Button signupB;
public void handleButtonClick (){
try {
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(getClass().getResource("sceneNotAvailable.fxml"));
/*
* if "fx:controller" is not set in fxml
* fxmlLoader.setController(NewWindowController);
*/
Scene scene = new Scene(fxmlLoader.load(), 630, 400);
Stage stage = new Stage();
stage.setTitle("New Window");
stage.setScene(scene);
stage.show();
} catch (IOException e) {
Logger logger = Logger.getLogger(getClass().getName());
logger.log(Level.SEVERE, "Failed to create new Window.", e);
}
}
}

binding progress bar with a method, javafx

I have a method which performs some task(reading, writing files and other tasks also) for almost 3 minutes.
I want to bind progress bar in javafx which can run with progress of the method.
This is my method
System.out.println("Going to load contract/security:"+new Date());
Map<Integer,FeedRefData> map = loadContractAndSecurityFromFile(loadFO);
addIndicesRefData(map);
BufferedWriter writer = createFile();
for (FeedRefData feedRefData : map.values()) {
try {
updateInstrumentAlias(map, feedRefData);
String refDataString = feedRefData.toString();
writer.write(refDataString, 0, refDataString.length());
writer.newLine();
writer.flush();
} catch (IOException e) {
e.printStackTrace();
log.info("Unable to write Quote Object to : " );
}
}
System.out.println("Ref Data File Generated:"+new Date());
For bind your method with progressbar you should do these steps :
Create a task which contains your method.
Create a thread which run this task.
Bind your progress property with your task property.
I made this simple example ,just change my code with your method code :
public class Bind extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) {
ProgressBar pb = new ProgressBar();
pb.setProgress(1.0);
Button button = new Button("start");
button.setOnAction((ActionEvent event) -> {
/*Create a task which contain method code*/
Task<Void> task = new Task<Void>() {
#Override
protected Void call() throws Exception {
File file = new File("C:\\Users\\Electron\\Desktop\\387303_254196324635587_907962025_n.jpg");
ByteArrayOutputStream bos = null;
try {
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[1024];
bos = new ByteArrayOutputStream();
for (int len; (len = fis.read(buffer)) != -1;) {
bos.write(buffer, 0, len);
updateProgress(len, file.length());
/* I sleeped operation because reading operation is quiqly*/
Thread.sleep(1000);
}
System.out.println("Reading is finished");
} catch (FileNotFoundException e) {
System.err.println(e.getMessage());
} catch (IOException e2) {
System.err.println(e2.getMessage());
}
return null;
}
};
Thread thread = new Thread(task);
thread.start();
/*bind the progress with task*/
pb.progressProperty()
.bind(task.progressProperty());
});
HBox box = new HBox(pb, button);
Stage stage = new Stage();
StackPane root = new StackPane();
root.getChildren().add(box);
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
}
Operation started :
Operation finished :
PS: I used Thread.sleep(1000) because my file is so small.You can remove it if your progress time is long.

javafx button.onclick() not working

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")
});

How to remove imageview from layout and add textview before converting the layout into image

Im developing one app, In that app, Im sharing image in social networks(Converting the layout into image) so my question is in my layout am having share icon, so i want remove that share icon and add textview to that layout before converting into image. can anyone give solution for my question. Thanks in advance
final View itemView = inflater.inflate(R.layout.fragment_layout, container, false);
itemView.setDrawingCacheEnabled(true);
itemView.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
itemView.layout(0, 0, 300, 400);
itemView.buildDrawingCache(true);
holder.share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Bitmap bitmap = Bitmap.createBitmap(mView.getWidth(), mView.getHeight(), Bitmap.Config.ARGB_8888);
Bitmap bitmap = Bitmap.createBitmap(itemView.getWidth(),itemView.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
itemView.draw(canvas);
Uri bmpUri = null;
try {
// output = new FileOutputStream(Environment.getExternalStorageDirectory() + "/path/to/file.png");
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), "share_image_" + System.currentTimeMillis() + ".png");
file.getParentFile().mkdirs();
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.close();
bmpUri = Uri.fromFile(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
sendIntent.putExtra(Intent.EXTRA_TEXT, SplashScreen.newstitleArray.get(SplashScreen.myCustomPosition));
sendIntent.setType("image/*");
context1.startActivity(sendIntent);
}
});

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