I have a little problem.
Here is my code
package email;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.stage.FileChooser;
public class Controller {
#FXML
public static Label daten;
#FXML
public static Button Datei;
#FXML
public TextField Trennzeichen;
static int i = 0;
#FXML
public void Datei(ActionEvent event) throws IOException, InterruptedException {
FileChooser fileChooser = new FileChooser();
File file = fileChooser.showOpenDialog(null);
FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("TXT files (*.txt)", "*.txt");
fileChooser.getExtensionFilters().add(extFilter);
String[] buffer = new String[9];
String[][] data = new String[2000][9];
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
String zeile = reader.readLine();
while (zeile != null) {
if ((zeile.substring(0, 1).equals("I")) || (zeile.substring(0, 1).equals("-"))) {
System.out.println("ha");
} else {
buffer = zeile.split(Trennzeichen.getText());
for (int t = 0; t < buffer.length; t++) {
data[i][t] = buffer[t];
}
++i;
daten.setText("" + i);
}
zeile = reader.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
I have a Label on my GUI, thats have to show me how many lines are in my txt file.
This works fine, but it is not live, the gui update after the work, before is the gui freezy..
How can I fix this in a task?
short again:
I have 1 label
filechooser thats load a txt file
the label have to show how many lines are reading after every line
See the question and my answer here: Display progress bar while compressing video file
JavaFX is a single thread GUI toolkit and if you do a long running task on the GUI Thread, it will freeze. So you should move the file reading to a background task as described in the linked question.
Edit: Sample skeleton solution
public void readFile() {
Label counter = new Label();
ReadFileTask task = new ReadFileTask();
counter.textProperty().bind(task.progressProperty().asString());
new Thread(task).start();
}
public class ReadFileTask extends Task<Void> {
#Override
protected Void call() throws Exception {
File file = new File(pathname); //TODO
long lines = Files.lines(file.toPath()).count();
long line = 0;
BufferedReader reader = new BufferedReader(new FileReader(file));
String zeile = null;
while ((zeile = reader.readLine()) != null) {
//TODO do the work
updateProgress(line++, lines);
}
return null;
}
}
Related
Hi I am a beginner programmer and I made a texteditor with a listview.
You can load a folder with your text files in the textview.
the problem I'm having is that I can't get the list to update after you save a file in the same folder.
I made a button for updating the list but I can't get it to work. I tried to remove and add the list again
with .clear and .setAll but it just removes the list.
Example of how to program looks like
Can someone help me to get the list to update when you push the "Refresh list" button?
Here is my code :
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.input.KeyCombination;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.web.HTMLEditor;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import java.io.*;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception {
//Create list with files
ObservableList files = FXCollections.observableArrayList();
ListView list = new ListView(files);
Button c = new Button("Load Folder");
c.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent e) {
DirectoryChooser dc = new DirectoryChooser();
dc.setInitialDirectory(new File(System.getProperty("user.home")));
File choice = dc.showDialog(primaryStage);
if (choice == null || !choice.isDirectory()) {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setHeaderText("Could not open directory");
alert.setContentText("The file is invalid.");
alert.showAndWait();
}
assert choice != null;
File[] selectedFiles = choice.listFiles();
files.removeAll(files);
files.addAll(selectedFiles);
list.setCellFactory(lv -> new ListCell<File>() {
#Override
protected void updateItem(File file, boolean empty) {
super.updateItem(file, empty);
setText(file == null ? null : file.getName());
}
});
}
});
// MENUS
MenuBar menuBar = new MenuBar();
Menu menuFile = new Menu("File");
Menu help = new Menu("help");
//Menu contents
// Menu FILE
MenuItem newfile = new MenuItem("New");
MenuItem open = new MenuItem("Open");
MenuItem save = new MenuItem("Save");
MenuItem export = new MenuItem("Export to txt");
MenuItem exit = new MenuItem("Exit");
newfile.setAccelerator(new KeyCodeCombination(KeyCode.N, KeyCombination.CONTROL_DOWN));
open.setAccelerator(new KeyCodeCombination(KeyCode.O, KeyCombination.CONTROL_DOWN));
save.setAccelerator(new KeyCodeCombination(KeyCode.S, KeyCombination.CONTROL_DOWN));
export.setAccelerator(new KeyCodeCombination(KeyCode.E, KeyCombination.CONTROL_DOWN));
exit.setAccelerator(new KeyCodeCombination(KeyCode.W, KeyCombination.CONTROL_DOWN));
//Menu HELP
MenuItem about = new MenuItem("About J4hN0te");
//Adding Menus in the box
menuBar.getMenus().addAll(menuFile, help);
menuFile.getItems().addAll(newfile, open, save, export, exit);
help.getItems().addAll(about);
//CREATE TEXTEDITOR
final HTMLEditor htmlEditor = new HTMLEditor();
htmlEditor.setPrefHeight(500);
htmlEditor.setPrefWidth(600);
//SCROLLIST
ScrollPane scrollpane = new ScrollPane();
scrollpane.getStyleClass().add("noborder-scroll-pane");
scrollpane.setContent(htmlEditor);
scrollpane.setFitToHeight(true);
// ABOUT WINDOW
String programName = "J4hN0te";
String version = "1.0 alpha";
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Om programmet");
alert.setHeaderText(programName + " - Version " + version + "\nEtt program skapat i kursen \"Intro Javaprogrammering\"\nYrkesAkademin Sundsvall - HT2019");
alert.setContentText("Vi som gjort programmet är:\n André Pähn \n Fredrik Lax");
// CREATE NEW FILE
newfile.setOnAction(ActionEvent -> {
htmlEditor.setHtmlText("");
});
//OPEN FILE
open.setOnAction(ActionEvent -> {
ArrayList<String> lines = new ArrayList<String>();
FileChooser fc = new FileChooser();
fc.getExtensionFilters()
.addAll(
new FileChooser.ExtensionFilter(".rtf files (*.rtf)", "*.rtf"),
new FileChooser.ExtensionFilter(".html files (*.html)", "*.html"));
File selectedFile = fc.showOpenDialog(null);
try (BufferedReader reader = new BufferedReader(new FileReader(new File(String.valueOf(selectedFile))))) {
String line;
while ((line = reader.readLine()) != null)
lines.add(line);
} catch (IOException e1) {
e1.printStackTrace();
}
lines.forEach(htmlEditor::setHtmlText);
});
// EXPORT FILE TO TXT
export.setOnAction(ActionEvent -> {
FileChooser fc = new FileChooser();
fc.getExtensionFilters()
.addAll(
new FileChooser.ExtensionFilter(".txt files (*.txt)", "*.txt"));
File savefile = fc.showSaveDialog(null);
try {
String htmlString = htmlEditor.getHtmlText();
Pattern pattern = Pattern.compile("<[^>]*>");
Matcher matcher = pattern.matcher(htmlString);
final StringBuffer sb = new StringBuffer(htmlString.length());
while (matcher.find()) {
matcher.appendReplacement(sb, System.lineSeparator());
}
matcher.appendTail(sb);
String fixedHtmlString = sb.toString().trim().replaceAll("(?m)^[ \t]*\r?\n", "");
FileWriter fw = new FileWriter(savefile);
fw.write(fixedHtmlString);
fw.close();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
});
//Save file to RTF or HTML
save.setOnAction(ActionEvent -> {
FileChooser fc = new FileChooser();
fc.getExtensionFilters()
.addAll(
new FileChooser.ExtensionFilter(".rtf files (*.rtf)", "*.rtf"),
new FileChooser.ExtensionFilter(".html files (*.html)", "*.html"));
File savefile = fc.showSaveDialog(null);
try {
FileWriter fw = new FileWriter(savefile);
fw.write(htmlEditor.getHtmlText());
fw.close();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
});
// EXIT PROGRAM
exit.setOnAction(ActionEvent -> {
System.exit(1);
});
// Open About window
about.setOnAction(ActionEvent -> alert.showAndWait());
//OPEN FILE IN EDITOR WITH DOUBLE CLICK
list.setOnMouseClicked((EventHandler<MouseEvent>) mouseEvent -> {
if (mouseEvent.getClickCount() == 2) {
File item = (File) list.getSelectionModel().getSelectedItem();
ArrayList<String> lines = new ArrayList<String>();
try (BufferedReader reader = new BufferedReader(new FileReader(new File(String.valueOf(item))))) {
String line;
while ((line = reader.readLine()) != null)
lines.add(line);
} catch (IOException e1) {
e1.printStackTrace();
}
lines.forEach(htmlEditor::setHtmlText);
}
});
// BUTTON FOR UPDATING THE LIST
Button refresh = new Button("Refresh List");
refresh.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent e) {
files.clear();
files.setAll();
}
});
//GENERAL WINDOW SETTINGS
StackPane stackPane = new StackPane();
SplitPane split = new SplitPane();
split.setDividerPositions(0.3);
split.getItems().add(list);
split.getItems().add(htmlEditor);
HBox hb = new HBox();
hb.getChildren().add(c);
hb.getChildren().add(refresh);
BorderPane borderpane = new BorderPane();
borderpane.setTop(menuBar);
borderpane.setCenter(split);
borderpane.setLeft(list);
borderpane.setRight(htmlEditor);
borderpane.setBottom(hb);
stackPane.getChildren().add(borderpane);
Scene scene = new Scene(stackPane);
primaryStage.setTitle("J4hN0te");
primaryStage.setScene(scene);
primaryStage.setMinWidth(900);
primaryStage.setMinHeight(700);
primaryStage.show();
}
}
You basically need to keep up with the current directory that is loaded into the list view. Follow currentFolderLoaded in the code.
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.input.KeyCombination;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.web.HTMLEditor;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import java.io.*;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main extends Application
{
File currentFolderLoaded = null;//Use to keep track of current folder loaded in ListView
public static void main(String[] args)
{
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception
{
//Create list with files
ObservableList files = FXCollections.observableArrayList();
ListView list = new ListView(files);
Button c = new Button("Load Folder");
c.setOnAction(new EventHandler<ActionEvent>()
{
#Override
public void handle(ActionEvent e)
{
DirectoryChooser dc = new DirectoryChooser();
dc.setInitialDirectory(new File(System.getProperty("user.home")));
File choice = dc.showDialog(primaryStage);
if (choice == null || !choice.isDirectory()) {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setHeaderText("Could not open directory");
alert.setContentText("The file is invalid.");
alert.showAndWait();
}
assert choice != null;
currentFolderLoaded = new File(choice.getAbsolutePath());//Assign the currently loaded folder to this variable
File[] selectedFiles = choice.listFiles();
files.removeAll(files);
files.addAll(selectedFiles);
list.setCellFactory(lv -> new ListCell<File>()
{
#Override
protected void updateItem(File file, boolean empty)
{
super.updateItem(file, empty);
setText(file == null ? null : file.getName());
}
});
}
});
// MENUS
MenuBar menuBar = new MenuBar();
Menu menuFile = new Menu("File");
Menu help = new Menu("help");
//Menu contents
// Menu FILE
MenuItem newfile = new MenuItem("New");
MenuItem open = new MenuItem("Open");
MenuItem save = new MenuItem("Save");
MenuItem export = new MenuItem("Export to txt");
MenuItem exit = new MenuItem("Exit");
newfile.setAccelerator(new KeyCodeCombination(KeyCode.N, KeyCombination.CONTROL_DOWN));
open.setAccelerator(new KeyCodeCombination(KeyCode.O, KeyCombination.CONTROL_DOWN));
save.setAccelerator(new KeyCodeCombination(KeyCode.S, KeyCombination.CONTROL_DOWN));
export.setAccelerator(new KeyCodeCombination(KeyCode.E, KeyCombination.CONTROL_DOWN));
exit.setAccelerator(new KeyCodeCombination(KeyCode.W, KeyCombination.CONTROL_DOWN));
//Menu HELP
MenuItem about = new MenuItem("About J4hN0te");
//Adding Menus in the box
menuBar.getMenus().addAll(menuFile, help);
menuFile.getItems().addAll(newfile, open, save, export, exit);
help.getItems().addAll(about);
//CREATE TEXTEDITOR
final HTMLEditor htmlEditor = new HTMLEditor();
htmlEditor.setPrefHeight(500);
htmlEditor.setPrefWidth(600);
//SCROLLIST
ScrollPane scrollpane = new ScrollPane();
scrollpane.getStyleClass().add("noborder-scroll-pane");
scrollpane.setContent(htmlEditor);
scrollpane.setFitToHeight(true);
// ABOUT WINDOW
String programName = "J4hN0te";
String version = "1.0 alpha";
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Om programmet");
alert.setHeaderText(programName + " - Version " + version + "\nEtt program skapat i kursen \"Intro Javaprogrammering\"\nYrkesAkademin Sundsvall - HT2019");
alert.setContentText("Vi som gjort programmet är:\n André Pähn \n Fredrik Lax");
// CREATE NEW FILE
newfile.setOnAction(ActionEvent -> {
htmlEditor.setHtmlText("");
});
//OPEN FILE
open.setOnAction(ActionEvent -> {
ArrayList<String> lines = new ArrayList<String>();
FileChooser fc = new FileChooser();
fc.getExtensionFilters()
.addAll(
new FileChooser.ExtensionFilter(".rtf files (*.rtf)", "*.rtf"),
new FileChooser.ExtensionFilter(".html files (*.html)", "*.html"));
File selectedFile = fc.showOpenDialog(null);
try (BufferedReader reader = new BufferedReader(new FileReader(new File(String.valueOf(selectedFile))))) {
String line;
while ((line = reader.readLine()) != null) {
lines.add(line);
}
}
catch (IOException e1) {
e1.printStackTrace();
}
lines.forEach(htmlEditor::setHtmlText);
});
// EXPORT FILE TO TXT
export.setOnAction(ActionEvent -> {
FileChooser fc = new FileChooser();
fc.getExtensionFilters()
.addAll(
new FileChooser.ExtensionFilter(".txt files (*.txt)", "*.txt"));
File savefile = fc.showSaveDialog(null);
try {
String htmlString = htmlEditor.getHtmlText();
Pattern pattern = Pattern.compile("<[^>]*>");
Matcher matcher = pattern.matcher(htmlString);
final StringBuffer sb = new StringBuffer(htmlString.length());
while (matcher.find()) {
matcher.appendReplacement(sb, System.lineSeparator());
}
matcher.appendTail(sb);
String fixedHtmlString = sb.toString().trim().replaceAll("(?m)^[ \t]*\r?\n", "");
FileWriter fw = new FileWriter(savefile);
fw.write(fixedHtmlString);
fw.close();
}
catch (Exception ex) {
System.out.println(ex.getMessage());
}
});
//Save file to RTF or HTML
save.setOnAction(ActionEvent -> {
FileChooser fc = new FileChooser();
fc.getExtensionFilters()
.addAll(
new FileChooser.ExtensionFilter(".rtf files (*.rtf)", "*.rtf"),
new FileChooser.ExtensionFilter(".html files (*.html)", "*.html"));
File savefile = fc.showSaveDialog(null);
try {
FileWriter fw = new FileWriter(savefile);
fw.write(htmlEditor.getHtmlText());
fw.close();
}
catch (Exception ex) {
System.out.println(ex.getMessage());
}
});
// EXIT PROGRAM
exit.setOnAction(ActionEvent -> {
System.exit(1);
});
// Open About window
about.setOnAction(ActionEvent -> alert.showAndWait());
//OPEN FILE IN EDITOR WITH DOUBLE CLICK
list.setOnMouseClicked((EventHandler<MouseEvent>) mouseEvent -> {
if (mouseEvent.getClickCount() == 2) {
File item = (File) list.getSelectionModel().getSelectedItem();
ArrayList<String> lines = new ArrayList<String>();
try (BufferedReader reader = new BufferedReader(new FileReader(new File(String.valueOf(item))))) {
String line;
while ((line = reader.readLine()) != null) {
lines.add(line);
}
}
catch (IOException e1) {
e1.printStackTrace();
}
lines.forEach(htmlEditor::setHtmlText);
}
});
// BUTTON FOR UPDATING THE LIST
Button refresh = new Button("Refresh List");
refresh.setOnAction(new EventHandler<ActionEvent>()
{
#Override
public void handle(ActionEvent e)
{
//Refresh the currently loaded folder
if(currentFolderLoaded != null)
{
File[] selectedFiles = currentFolderLoaded.listFiles();
files.setAll(selectedFiles);
}
else
{
System.out.println("NO DIRECTORY CHOSEN!");
}
}
});
//GENERAL WINDOW SETTINGS
StackPane stackPane = new StackPane();
SplitPane split = new SplitPane();
split.setDividerPositions(0.3);
split.getItems().add(list);
split.getItems().add(htmlEditor);
HBox hb = new HBox();
hb.getChildren().add(c);
hb.getChildren().add(refresh);
BorderPane borderpane = new BorderPane();
borderpane.setTop(menuBar);
borderpane.setCenter(split);
borderpane.setLeft(list);
borderpane.setRight(htmlEditor);
borderpane.setBottom(hb);
stackPane.getChildren().add(borderpane);
Scene scene = new Scene(stackPane);
primaryStage.setTitle("J4hN0te");
primaryStage.setScene(scene);
primaryStage.setMinWidth(900);
primaryStage.setMinHeight(700);
primaryStage.show();
}
}
There are some things you need to change in your code.
You need to create a File object to store the selected folder, so
you can reload it every time you need to refresh.
In the setOnAction() method of the refresh button you call the
setAll() method of files with no arguments. This methods clears the
list and adds all the elements given. That's why the list is empty
every time you refresh.
Now the setOnAction() method of the refresh button would be like
this:
public void handle(ActionEvent e) {
files.setAll(directory.listFiles());
}
I use a CLI program regularly which is accessed through a docker container. Once I enter the container, I can start using my CLI program in question. The issue I'm having is I want to continue to interact with the same command line instance. Basically I'm trying to create a GUI program that will run "on top" of a CLI program. I just don't know how to keep sending commands to the same CLI instance:
List<String> command = new ArrayList<String>();
command.add("cmd.exe" );
command.add("/c");
command.add("docker-compose up -d");
System.out.println(command);
ProcessBuilder builder = new ProcessBuilder(command);
builder.inheritIO();
Map<String, String> environ = builder.environment();
Process process = builder.start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
command.clear();
command.add("cmd.exe" );
command.add("/c");
command.add("docker ps");
System.out.println(command);
process = builder.start();
is = process.getInputStream();
isr = new InputStreamReader(is);
br = new BufferedReader(isr);
while ((line = br.readLine()) != null) {
System.out.println(line);
}
But this isn't working the way I would like it to. Above, you'll see I'm running two commands: docker-compose up -d and then docker ps. But I don't think they are running in the same instance. So if I were to change the directory in the first command, it's not going to remember the directory for the second command.
Also, it seems to be running my commands in reverse order from the order in the code.
Instances of class ProcessBuilder are intended to be short-lived, in my opinion. I don't think creating a new instance each time you want to create a new process wastes memory or other resources - but I'm only guessing.
In any case, to re-use a ProcessBuilder instance in order to execute several processes, you simply use its methods, like command(String...)
I wrote a small Swing app that lets the user enter a [operating system] command and displays that command's output. It's not production ready, but I hope it's enough to get you going.
Note that creating and handling a Process in java code is not simple nor intuitive. The article When Runtime.exec() won't helped me a lot. It is an ancient article, but nonetheless still relevant (again, in my opinion). Simply replace references to class Runtime in the article with class ProcessBuilder since the article was written before ProcessBuilder was added to the JDK.
Here is the code of my app. Please refer to the above-mentioned article in order to understand the ProcessBuilder related code. In order to understand the Swing code, I recommend the tutorial Creating a GUI With JFC/Swing
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
public class ProcExec implements ActionListener, Runnable {
private static final String CLEAR = "Clear";
private static final String EXIT = "Exit";
private static final String RUN = "Run";
private JTextArea commandOutput;
private JTextArea textArea;
private ProcessBuilder procBuilder;
public ProcExec() {
procBuilder = new ProcessBuilder();
}
public void actionPerformed(ActionEvent actionEvent) {
String actionCommand = actionEvent.getActionCommand();
if (CLEAR.equals(actionCommand)) {
textArea.setText("");
}
else if (EXIT.equals(actionCommand)) {
System.exit(0);
}
else if (RUN.equals(actionCommand)) {
try {
execute();
}
catch (Exception x) {
x.printStackTrace();
}
}
}
public void run() {
createAndDisplayGui();
}
private void createAndDisplayGui() {
JFrame frame = new JFrame("Process Executor");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(createTopPanel(), BorderLayout.PAGE_START);
frame.add(createCommandPanel(), BorderLayout.CENTER);
frame.add(createButtonsPanel(), BorderLayout.PAGE_END);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JButton createButton(String text, int mnemonic, String tooltip) {
JButton button = new JButton(text);
button.setMnemonic(mnemonic);
button.setToolTipText(tooltip);
button.addActionListener(this);
return button;
}
private JPanel createButtonsPanel() {
JPanel buttonsPanel = new JPanel();
buttonsPanel.add(createButton(RUN, KeyEvent.VK_R, "Run entered command."));
buttonsPanel.add(createButton(CLEAR, KeyEvent.VK_C, "Removes entered command."));
buttonsPanel.add(createButton(EXIT, KeyEvent.VK_X, "Exit application."));
return buttonsPanel;
}
private JSplitPane createCommandPanel() {
textArea = new JTextArea(30, 40);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
JScrollPane cmdScrollPane = new JScrollPane(textArea);
commandOutput = new JTextArea(30, 80);
JScrollPane outputScrollPane = new JScrollPane(commandOutput);
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
cmdScrollPane,
outputScrollPane);
return splitPane;
}
private JPanel createTopPanel() {
JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.LEADING));
JLabel label = new JLabel("Enter a command...");
topPanel.add(label);
return topPanel;
}
private int execute() throws IOException, InterruptedException {
commandOutput.setText("");
String raw = textArea.getText();
String[] words = raw.split(" ");
String[] command = new String[words.length + 2];
command[0] = "cmd.exe";
command[1] = "/C";
System.arraycopy(words, 0, command, 2, words.length);
procBuilder.command(command);
Process proc = procBuilder.start();
ProcHandler stdout = new ProcHandler(proc.getInputStream());
ProcHandler stderr = new ProcHandler(proc.getErrorStream());
Thread stdoutThread = new Thread(stdout);
stdoutThread.start();
Thread stderrThread = new Thread(stderr);
stderrThread.start();
int status = proc.waitFor();
stderrThread.join();
stdoutThread.join();
return status;
}
private class ProcHandler implements Runnable {
private BufferedReader streamReader;
public ProcHandler(InputStream is) {
InputStreamReader isr = new InputStreamReader(is);
streamReader = new BufferedReader(isr);
}
public void run() {
try {
String line = streamReader.readLine();
while (line != null) {
SwingUtilities.invokeLater(new StreamLine(line));
line = streamReader.readLine();
}
}
catch (Exception x) {
throw new RuntimeException("Stream reading failed.", x);
}
}
}
private class StreamLine implements Runnable {
private final String text;
public StreamLine(String txt) {
text = txt + "\n";
}
public void run() {
ProcExec.this.commandOutput.append(text);
}
}
public static void main(String[] args) {
ProcExec instance = new ProcExec();
EventQueue.invokeLater(instance);
}
}
I have the following code in which I want to read what is in the text file and display in textField2 weather it has changed or not... If it has, then I need it to continue. If it hasn't, then I need it to check again until the file has been changed to empty. Can anyone help? Here is my code:
package application;
import javafx.event.ActionEvent;
import javafx.scene.control.TextField;
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.Parent;
import javafx.fxml.FXMLLoader;
import javafx.fxml.FXML;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Main extends Application {
#Override
public void start(Stage primaryStage) {
try {
// BorderPane root = new BorderPane();
Parent root = FXMLLoader.load(getClass().
getResource("Root.fxml"));
Scene scene = new Scene(root,550,400);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
#FXML
private TextField textField;
#FXML
private TextField textField2;
#FXML
protected void onClick(ActionEvent event) throws IOException {
BufferedWriter writer = null;
try {
//create a temporary file
// This will output the full path where the file will be written to...
writer = new BufferedWriter(new FileWriter("C:/Users/Custom/Documents/Sample.txt"));
writer.write(textField.getText());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// Close the writer regardless of what happens...
writer.close();
} catch (Exception e) {
}
while (readFile("C:/Users/Custom/Documents/Sample.txt") != ""){
textField2.setText("Waiting...");
}
textField2.setText("Done!");
}
}
String readFile(String fileName) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(fileName));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append("\n");
line = br.readLine();
}
return sb.toString();
} finally {
br.close();
}
}
}
you can check the time stamp of file to determine whether it has changed or not.
Sample code :
Long fileLastModified;
File file = new File("file");
if (!file.exists()) {
syserr
}
if (file.lastModified() <= this.fileLastModified) {
return oldValue;
}
this.fileLastModified = file.lastModified();
Also, you should use threads as commented by redflar3
Hi you can make a timer to check the file once every 2 seconds or so a snippet goes here
new java.util.Timer().schedule(
new java.util.TimerTask() {
#Override
public void run() {
//Read your file
if(fileEmpty){
//Update your textfiled
cancel(); //Stops this timer
}
}
},
0,2000);
once your task is done just use purge(); to clear out all cancelled timers
hope this helps
I would like to save an ArrayList's content to file (the user should choose the .txt's location) but I am not sure how to do that since that code does not work properly.
Do you have any idea how to do that?
package vizsgaquiz;
import java.io.File;
import java.util.ArrayList;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
public class VizsgaQuiz extends Application {
ArrayList<String> kerdeslista = new ArrayList<String>();
String a ="a";
#Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("Foablak.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.setTitle("Quiz Játék");
stage.show();
save();
}
public void save(){
kerdeslista.add(a);
FileChooser fileChooser = new FileChooser();
//Set extension filter
FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("TXT files (*.txt)", "*.txt");
fileChooser.getExtensionFilters().add(extFilter);
//Show save file dialog
File file = fileChooser.showSaveDialog(stage);
if(file != null){
SaveFile(kerdeslista, file);
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
There are several issues that may be causing this problem. For starters, this code wouldn't compile. This is because you call the variable stage in the method save which "died" in the method start. To call stage in save, you either need to pass it to save or save it as a field. The second issue is that the method SaveFile doesn't seem to exist. An example of SaveFile might look something like the code included below. Please note that I updated the method save to take in a Stage and I changed the name of the method SaveFile to saveFile to match Java naming conventions. Also, the code below prints each value of the arraylist on a new line, which you may not want.
package vizsgaquiz;
import java.io.File;
import java.io.PrintWriter;
import java.util.ArrayList;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
public class VizsgaQuiz extends Application {
ArrayList<String> kerdeslista = new ArrayList<String>();
String a ="a";
#Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("Foablak.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.setTitle("Quiz Játék");
stage.show();
save(stage);
}
public void save(Stage stage){
kerdeslista.add(a);
FileChooser fileChooser = new FileChooser();
//Set extension filter
FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("TXT files (*.txt)", "*.txt");
fileChooser.getExtensionFilters().add(extFilter);
//Show save file dialog
File file = fileChooser.showSaveDialog(stage);
if(file != null){
saveFile(kerdeslista, file);
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
public static void saveFile(ArrayList<String> list, File file) {
try {
PrintWriter out = new PrintWriter(file);
for (String val : list)
out.println(val + "\n");
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Here is an example how to save a new file to specified directory and name of file from FileDialog , Strings taken from a vector of Strings.It works for me !
public static void SaveFileTo(Vector<String> myLines) {
FileOutputStream f = null;
DataOutputStream h = null;
FileDialog d = new FileDialog(new JFrame(), "Save", FileDialog.SAVE);
d.setVisible(true);
String dir;
dir = d.getDirectory();
File oneFile = new File(dir + d.getFile());
try {
oneFile.createNewFile();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
f = new FileOutputStream(oneFile);
h = new DataOutputStream(f);
for (String de : myLines) {
h.writeBytes(de);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
h.close();
f.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I'm making a program that requires to save user input. So I would like to know how to save JTextArea to text file and when you close and re-open program text is still in JTextArea.
Also sorry for my bad grammar.
package main;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.border.EtchedBorder;
public class main extends JFrame {
JLabel statusbar;
public main() {
initUI();
}
public final void initUI() {
JPanel panel = new JPanel();
statusbar = new JLabel("");
statusbar.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));
panel.setLayout(null);
JTextArea area1;
area1 = new JTextArea(90, 25);
area1.setBounds(20, 20, 200, 25);
area1.setBackground(Color.white);
area1.setForeground(Color.BLACK);
area1.setText("");
panel.add(area1);
add(panel);
add(statusbar, BorderLayout.SOUTH);
setTitle("Viskis");
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
JButton o = (JButton) e.getSource();
String label = o.getText();
statusbar.setText("");
} }
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
main ms = new main();
ms.setVisible(true);
new main();
}
});
}
}
Here are some helper methods to help you read and write from Files. Look in the JavaDoc for getText() and setText() for getting and setting the text of the JTextArea.
I recommend reading the SwingWorker tutorials and using these methods in a SwingWorker, lest you lock up your GUI while saving/reading the Files
/**
* Writes a String text to a File specified by filename
*
* #param filename The filename/path of the File we would like to write the text to
* #param text The text to write to the File
*
*/
public static void writeToFile(String filename, String text) {
BufferedWriter writer = null; // This could go in a try-with-resources if you wanna get fancy
try {
writer = new BufferedWriter(new FileWriter(new File(filename))); // Open a File for writing
writer.write(text); // write the text to the file
} catch ( IOException e) {
/* We could not open the File for writing, or could not write to the File */
} finally {
try {
if (writer != null) {
writer.close(); // we are done writing to the File, close the connection
}
} catch (IOException e) {
/* We could not close the connection to the File */
}
}
}
/**
* Reads all lines from a File specified by filename
*
* #param filename The filename/path of the File we would like to read text from
*
* #return An list of Strings containing each line of the File
*/
public static List<String> readFromFile(String filename) {
BufferedReader reader = null; // This could go in a try-with-resources if you wanna get fancy
List<String> lines = new ArrayList<String>();
try {
reader = new BufferedReader(new FileReader(new File(filename))); // Open a File for writing
while ((line = reader.readLine()) != null) {
lines.add(line);
}
} catch (IOException e) {
/* We could not open the File for reading, or could not read from the File */
} finally {
try {
if (reader != null) {
reader.close(); // we are done reading from the File, close the connection
}
} catch (IOException e) {
/* We could not close the connection to the File */
}
}
return lines;
}
Write and read file on a swing thread is not recommanded. Use mvc pattern. Create a data model with field binded to your component. Create an adapter to update model and write file
Then your component will always up to date with your model
Use model to write data(with the adapter) and read file will update your model with the adapter
For exemple, Focus listener will call adapter to do the task. Or you can use an obseevee pattern when you Object if modified.
This code worked for me with 'nam' as the current date and 'name' an input in a jTextField.
try {
con=Connect.ConnectDB();
pst.execute();
Date date=new Date();
SimpleDateFormat sd=new SimpleDateFormat("dd-mm-yyyy-h-m-s");
String nam= sd.format(date);
String name=CaseNoField.getText();
CaseNoField.setText("");
FileWriter writer=new FileWriter( "C:\\path"+name+"("+nam+")"+".txt");
BufferedWriter bw=new BufferedWriter( writer );
JCaseArea.write( bw );
bw.close();
JCaseArea.setText("");
JCaseArea.requestFocus();
JOptionPane.showMessageDialog(null, "Case Saved");
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}