Essentially, I'm trying to collect data for a string and use it in another method. Whatever I've tried hasn't seemed to work. Please check out my code and tell me what to do.
I've tried to declare the string as a public string, but since it is in a method I can't.
My goal is to transfer the string "application_1" to button3's setOnAction method.
#Override
public void start(Stage primaryStage) throws Exception {
window = primaryStage;
window.setTitle("myDesktop");
window.setOnCloseRequest(e -> closeProgram());
button = new Button("Setup MyDesktop");
button3 = new Button("Start Test Application");
button2 = new Button("Choose Wheel Applications");
button2.setOnAction(e -> {
JFileChooser jfc = new JFileChooser();
jfc.showDialog(null, "Please select a file.");
jfc.setVisible(true);
File filename = jfc.getSelectedFile();
String application_1 = filename.getName();
if (application_1.endsWith(".exe")) {
System.out.println("File successfully chosen!");
} else {
System.out.println("File is not an application!");
System.out.println("Please choose another file!");
System.out.println("Issue Alert Box here...");
}
if (application_1 == null) {
System.out.println("No file selected!");
}
});
button.setOnAction(e -> {
AlertBox.display("Alert", "Save file?");
});
button3.setOnAction(e -> {
Runtime runtime = Runtime.getRuntime();
try {
Process process = runtime.exec("name_of_file");
} catch (IOException e1) {
e1.printStackTrace();
}
});
I want the string to be able to be used by the code
button3.setOnAction(e -> {
// code
});
Should work:
#Override
public void start(Stage primaryStage) throws Exception {
window = primaryStage;
window.setTitle("myDesktop");
window.setOnCloseRequest(e -> closeProgram());
String application_1 = "";
button = new Button("Setup MyDesktop");
button3 = new Button("Start Test Application");
button2 = new Button("Choose Wheel Applications");
button2.setOnAction(e -> {
JFileChooser jfc = new JFileChooser();
jfc.showDialog(null, "Please select a file.");
jfc.setVisible(true);
File filename = jfc.getSelectedFile();
application_1 = filename.getName();
if (application_1.endsWith(".exe")) {
System.out.println("File successfully chosen!");
} else {
System.out.println("File is not an application!");
System.out.println("Please choose another file!");
System.out.println("Issue Alert Box here...");
}
if (application_1 == null) {
System.out.println("No file selected!");
}
});
button.setOnAction(e -> {
AlertBox.display("Alert", "Save file?");
});
button3.setOnAction(e -> {
Runtime runtime = Runtime.getRuntime();
System.out.println(application_1); //here you can use the variable
try {
Process process = runtime.exec("name_of_file");
} catch (IOException e1) {
e1.printStackTrace();
}
});
Since you don't have control over the actual event that's created when the button is hit you cannot pass it directly (well, maybe you could add a tag to the button or something similar - I never used javafx).
But nothing prevents you from introducing an object-level variable to hold your string(s).
class YourClass {
private String myString = "";
public void start(Stage primaryStage) throws Exception {
// ...
button2.setOnAction(e -> {
this.myString = "application_1";
});
// ...
button3.setOnAction(e -> {
System.out.println(this.myString);
});
}
}
Alternatively, if your variable is final or effectively final you can just use it in your anonymous function:
class YourClass {
public void start(Stage primaryStage) throws Exception {
// ...
final String myString = "application_1";
// ...
button3.setOnAction(e -> {
System.out.println(myString);
});
}
}
Related
I'm trying to get the value from the Textfield named getText. However, it doesn't let me get the value since it's inside the handler. Is there a way I can return or save this value?
Here's the code:
EventHandler<ActionEvent> handler2 = k -> {
if (!getText.getText().isEmpty()) {
String NameOfFile = getText.getText();
finallyname[0]=NameOfFile;
StringBuilder sb1 = new StringBuilder(NameOfFile);
sb1.append(".txt");
String newStr=sb1.toString();
System.out.println(newStr);
name.setText(newStr);
stage.show();
stage1.close();
theWindow.getChildren().addAll(v1);
r1.setOnMouseClicked(ME -> {
if (ME.getButton().equals(MouseButton.PRIMARY) && ME.getClickCount() == 2) {
try {
Parent newtxtFile = FXMLLoader.load(getClass().getResource("txtFile.fxml"));
Stage stagenew = new Stage();
Scene scenenew = new Scene(newtxtFile);
stagenew.setTitle(getText.getText());
stagenew.setScene(scene);
stagenew.show();
} catch (IOException ex) {
}
}
});
} else {
l2.setTextFill(Color.RED);
l2.setText("Please enter a value first.");
}
};
So I am remaking my kinda complex console program to GUI. However, I am very unexperienced JavaFX user.
Label cityNameLabel = (Label) scene.lookup("#cityNameLabel");
cityNameLabel.setText("No text");
Button startButton = (Button) scene.lookup("#startButton");
Here I have my Label successfully initiated. At this moment I can still use cityNameLabel.setText(); and it is gonna work.
This continues:
startButton.setOnAction(e -> {
String enteredUrl = linkField.getText();
if(isValidUrl(enteredUrl)) {
try {
cityNameLabel.setText("Test");
doJob(enteredUrl, cityNameLabel);
} catch (IOException e1) {
e1.printStackTrace();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}.........
When I try to change the label here it won't happen. What I actually need to do is to reference the cityNamelLabel to doJob() method and I want to doJob() method to change it (once it finds the name of the city).
Can anyone give a me a solution that would allow me to do what I want to do? (changing it afterwards from doJob();). Thank you!
EDIT: Here I post my attemp of minimal version. I hope it is enough
package net.maty;
public class Katastr extends Application {
final String programName = "KatastRED";
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage mainStage) throws Exception {
try {
mainStage.setTitle(programName);
mainStage.setResizable(false);
BorderPane root = (BorderPane)FXMLLoader.load(getClass().getResource("Katastr.fxml"));
Scene scene = new Scene(root,800,500);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
ChoiceBox threadNumberBox = (ChoiceBox) scene.lookup("#threadNumberBox");
threadNumberBox.getSelectionModel().select(5);
TextField linkField = (TextField) scene.lookup("#linkField");
//debug
linkField.setText("https://regiony.kurzy.cz/katastr/stary-kolin/objekty?strana=");
//
Text cityNameText = (Text) scene.lookup("#cityNameText");
Button startButton = (Button) scene.lookup("#startButton");
//HERE IS THE THING. EVERYTHING WORKS WELL EXCEPT THE FACT I CANT CHANGE CITYNAMETEXT
startButton.setOnAction(e -> {
String enteredUrl = linkField.getText();
if(isValidUrl(enteredUrl)) {
try {
cityNameText.setText("Example that will not show because it doesnt work.");
doJob(enteredUrl, cityNameText);
} catch (IOException e1) {
e1.printStackTrace();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
else {
Alert alert = new Alert(AlertType.ERROR);
alert.setTitle("Chyba!");
alert.setHeaderText(null);
alert.setContentText("Chybně zadané URL!");
alert.showAndWait();
}
});
mainStage.setScene(scene);
mainStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void doJob(String validatedUrl, Text cityNameText) throws IOException, InterruptedException {
Scanner in = new Scanner(System.in);
String url = validatedUrl;
String cityName = getCityName(url);
cityNameText.setText(cityName);
List<String> parcelLinks = getParcelLinks(url);.....
}
public static List<String> getParcelLinks(String url) throws IOException{
}
public static List<String> getAdressesFromPage(Document doc) {
}
public static List<String> createParcelUrls(List<String> links) throws IOException {
}
public static boolean isValidUrl(String url) {
}
public static String getCityName(String url) throws IOException {
}
}
runEncrypt.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
File inputFile = new File("/Users/aktasberk/Desktop/hey");
File encryptedFile = new File("/Users/aktasberk/Desktop/Encrypted_"+inputFile.getName());
File decryptedFile = new File("/Users/aktasberk/Desktop/Decrypted_"+inputFile.getName());
try {
String key = "16BitKeyIsHere16";
CryptoUtils.encrypt(key, inputFile, encryptedFile);
CryptoUtils.decrypt(key, encryptedFile, decryptedFile);
} catch (CryptoException ex) {
System.out.println(ex.getMessage());
ex.printStackTrace();
}
}
});
Okay so I have an encryption&decryption project, the encrypting and decrypting works fine but I have some problems using FileInputStream to get the file from directory, I have a browse button to do that but could not make it work, so as you can see in the code I get the input file manually.
Below here is my browse button opening up a file dialog to let me choose a file.
browseEncrypt.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
File selectedFile = chooseEncrypt.showOpenDialog(primaryStage);
if (selectedFile != null) {
encryptPath.setText(selectedFile.getPath());
primaryStage.show();
}
}
});
I need to get the file from browse button instead of declaring it manually in the code, I can be more specific if info is needed, thanks.
Delete local:
File encryptedFile = new File("/Users/aktasberk/Desktop/Encrypted_"+inputFile.getName());
Make global
File encryptedFile;
Then:
browseEncrypt.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
File selectedFile = chooseEncrypt.showOpenDialog(primaryStage);
if (selectedFile != null) {
encryptPath.setText(selectedFile.getPath());
encryptedFile = selectedFile;//Add This!
primaryStage.show();//Not sure why this is here?
}
}
});
I faced with issue during invoking java.awt.FileDialog with next snippet of code. OS X spinner is constantly spinning and nothing change (Finder doesn't open)
public class Main extends Application {
#Override
public void start(Stage primaryStage) throws Exception{
primaryStage.setTitle("CSV Parser");
Button button = new Button();
button.setText("Import Translations");
button.setOnAction(event -> {
String openFile = openFile();
System.out.println("Open file " + openFile);
});
VBox vbox = new VBox();
vbox.setPadding(new Insets(10));
vbox.setSpacing(8);
vbox.getChildren().add(button);
primaryStage.setScene(new Scene(vbox));
primaryStage.show();
}
public static String openFile() {
JFrame parentFrame = getJFrame("JFrame");
String osName = System.getProperty("os.name");
if (osName.toLowerCase().contains("mac")) {
FileDialog fileDialog = new FileDialog(parentFrame);
FilenameFilter csvFilter = (dir, name) -> name.endsWith(".csv");
fileDialog.setFilenameFilter(csvFilter);
fileDialog.setFile("*.csv");
fileDialog.setMode(FileDialog.LOAD);
String dirHome = System.getProperty("user.home");
fileDialog.setDirectory(dirHome);
fileDialog.setVisible(true);
boolean isShowing = fileDialog.isShowing();
if (isShowing) {
File fileToOpen = new File(fileDialog.getFile());
String path = fileToOpen.getAbsolutePath();
parentFrame.dispatchEvent(new WindowEvent(parentFrame, WindowEvent.WINDOW_CLOSING));
return path;
} else {
parentFrame.dispatchEvent(new WindowEvent(parentFrame, WindowEvent.WINDOW_CLOSING));
return null;
}
}
return null;
}
private static JFrame getJFrame(String name) {
JFrame parentFrame = new JFrame(name);
parentFrame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
ex.printStackTrace();
}
return parentFrame;
}
public static void main(String[] args) {
launch(args);
}
}
I need just to have ability to select a file with appropriate extension (not a folder), the appearance of dialog doesn't have a bi sense, but I want to implement it without any external libs.
I would be appreciate for any help.
Your dialog is linked to a new frame (that is not visible)... You should either use null argument to dialog's constructor or the reference of the current frame the dialog should be logically linked to.
I am trying to add a slider on my page like progress bar. But my code is not working well.
My task is when I am going to copy something from one location to another I want to display a progress bar on my page.
So in javaFx I wrote following task but it is not working well. That code runs but I want show the work in percentage like 30%, 50% and "finish". But my code fails to gives me like requirement so please help me.
My code is:
1.Declaration of progress bar and progress indicator
#FXML
final ProgressBar progressBar = new ProgressBar();
#FXML
final ProgressIndicator progressIndicator = new ProgressIndicator();
2.Assign values when I click on copy button.
#FXML
private void handleOnClickButtonAction(MouseEvent event) {
if (fromLabel.getText().isEmpty()
|| toLabel.getText().isEmpty()
|| fromLabel.getText().equalsIgnoreCase("No Directory Selected")
|| toLabel.getText().equalsIgnoreCase("No Directory Selected")) {
// Nothing
} else {
progressBar.setProgress(0.1f);
progressIndicator.setProgress(progressBar.getProgress());
this.directoryCount.setText("Please Wait !!!");
}
}
This code shows me only 10% completion an then directly shows "done", but I want whole process in percentage like 10,20,30,.. etc and then "done".
My copy code:
double i = 1;
while (rst.next()) {
File srcDirFile = new File(fromLabel.getText() + "/" + rst.getString("nugget_media_files"));
File dstDirFile = new File(toLabel.getText() + "/" + rst.getString("nugget_media_files"));
File dstDir = new File(toLabel.getText() + "/" + rst.getString("nugget_directory"));
if (srcDirFile.lastModified() > dstDirFile.lastModified()
|| srcDirFile.length() != dstDirFile.length()) {
copyDirectory(srcDirFile, dstDirFile, dstDir);
}
this.currentNuggetCount = i / this.nuggetFolderSize;
System.out.println("Nugget Count : " + this.currentNuggetCount);
Platform.runLater(new Runnable() {
#Override
public void run() {
progressBar.setProgress(1.0f);
progressIndicator.setProgress(progressBar.getProgress());
}
});
++i;
}
This is the copyDirectory method:
private static void copyDirectory(File srcDir, File dstDir,File destNugget) {
System.out.println(srcDir+" >> "+dstDir);
if(!destNugget.exists()) {
destNugget.mkdirs();
}
if (srcDir.isDirectory()) {
if (!dstDir.exists()) {
dstDir.mkdirs();
}
String[] children = srcDir.list();
for (int i=0; i<children.length; i++) {
copyDirectory(new File(srcDir, children[i]),
new File(dstDir, children[i]),
destNugget);
}
} else {
InputStream in = null;
try {
in = new FileInputStream(srcDir);
OutputStream out = new FileOutputStream(dstDir);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
} catch (IOException ex) {
System.out.println("Exceptio "+ex);
} finally {
try {
in.close();
} catch (IOException ex) {
System.out.println("Exceptio "+ex);
}
}
}
}
Try this code. It will give you Progress bar with progress indicator which depends on the slider control.
public class Main extends Application {
#Override
public void start(Stage stage) {
Group root = new Group();
Scene scene = new Scene(root);
stage.setScene(scene);
stage.setTitle("Progress Controls");
final Slider slider = new Slider();
slider.setMin(0);
slider.setMax(50);
final ProgressBar pb = new ProgressBar(0);
final ProgressIndicator pi = new ProgressIndicator(0);
slider.valueProperty().addListener(new ChangeListener<Number>() {
public void changed(ObservableValue<? extends Number> ov,
Number old_val, Number new_val) {
pb.setProgress(new_val.doubleValue()/50);
pi.setProgress(new_val.doubleValue()/50);
}
});
final HBox hb = new HBox();
hb.setSpacing(5);
hb.setAlignment(Pos.CENTER);
hb.getChildren().addAll(slider, pb, pi);
scene.setRoot(hb);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
You must enter your code inside a Task and set within UpdateProgress method. Before you run the Task you have to set progressBar.progressProperty (). Bind (task.progressProperty ());
This is an example:
TaskTest