Writing a character on another java application on button click? - java

I am a Java programmer and new to JavaFx.I want to create a virtual keyborad. I can make everything like buttons,layout,stage,scene everything.I also know using setText() method which can write text on the same java applicatton,but the question is that how do i make understand computer or program(in javafx or java not in swings) that on button click(ie on setOnAction()),it has to write a character on any 'another' java application (such as notepad,wordpad,etc). Is there is any class or interface that i have to extends or implements respectively or is there is any method which can help? I had explored the internet but was unable to find something helpful.

If you have set all the buttons in your controller you can do like this :
//I supposed you named you 'button_a' your
#FXML
Button button_a;
#Override
public void initialize(URL location, ResourceBundle resources) {
button_a.setOnAction(event->{
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter("file.txt")); //or new File("c:/users/.../.../file.txt");
writer.write(button_a.getText()); //will give the letter you write on the button : the letter of the keyboard
} catch (IOException e) {
System.err.println("IOError on write");
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
System.err.println("IOError on close");
e.printStackTrace();
}
}
}
});
}
An easier way could be that : You have surely put all your buttons in a container, a GridPane would be good because you can put all into ONE container (and put ONLY the buttons or you'll need to check it's a button each time in the loop), and then iterate over the children of the GridPane (the buttons) :
#FXML
GridPane grid;
#Override
public void initialize(URL location, ResourceBundle resources) {
String fileName = "test.txt";
for(Node button : grid.getChildren()){
((Button)button).setOnAction(event->{
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(fileName)); //or new File("c:/users/.../.../file.txt");
writer.write(((Button)button).getText()); //will give the letter you write on the button : the letter of the keyboard
} catch (IOException e) {
System.err.println("IOError on write");
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
System.err.println("IOError on close");
e.printStackTrace();
}
}
}
});
}
}
Hope this helps

Related

Append to csv in for loop using filewriter

I am working on a debuging csv output inside an event driven java application. I define my filewriter like this on init.
public File csvFile;
public FileWriter fileWriter;
then I initialies them
this.csvFile = new File("c:\\missingitems.csv");
this.fileWriter = null;
try {
this.fileWriter = new FileWriter(this.csvFile);
StringBuilder line = new StringBuilder();
line.append("Date, ItemId");
line.append("\n");
this.fileWriter.write(line.toString());
} catch (IOException e) {
e.printStackTrace();
}
then within my actual program logic this gets called for every timestep in my data
for(Long item : this.items) {
StringBuilder line = new StringBuilder();
line.append(event.getDateTime().toLocalDate().toString() + "," +item.intValue());
line.append("\n");
try {
this.fileWriter.write(line.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
on exit of my program I call
try {
this.fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
However this seems to be only working if i close the filewriter after each append. Is there a way of keeping the file open and just append to it, I would also like to not loose my data in case my application crashes. I am a python guy and not super familiar with java.

How can I resume code where I left off after FILENOTFOUNDEXCEPTION is thrown

I am writing a file into a directory. There might be the chance that the directory becomes unreachable.
What I want to do is..
As the code is writing to the file, if the directory becomes unreachable or a file not found exception is thrown I want it to keep checking if the directory exists and continue where I left off after the directory exists again.
After some time if the directory does not come back up then I would shut the program down.
My problem is that when a file not found exception is thrown the program just shuts down all together. Here is my code:
public class BusStopsProcessor implements Runnable
{
private BlockingQueue<Bus<buses>> busQueue;
private Bus<buses> BusObject;
public BusStopsProcessor(BlockingQueue<Bus<buses>> busQueue)
{
this.busQueue = busQueue;
}
#Override
public void run()
{
try
{
String path = "C:\\Users\\Me\\Documents\\";
File file = new File(path + "busStopsFile.txt");
FileWriter fw = new FileWriter(file, true);
CSVWriter writer = new CSVWriter(fw, '|', CSVWriter.NO_QUOTE_CHARACTER);
while(true)
{
BusObject = busQueue.take();
//each bus object should have a bus date if it does not then it is a
//poison bus object.
if(BusObject.getBusDate() != null)
{
createBusFile(BusObject, writer);
else
{
try
{
//Finished processing bus stops so close writer.
writer.close();
fw.close();
break;
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt();
e.printStackTrace();
}
catch (FileNotFoundException e)
{
//If a FILENOTFOUND exception is thrown here I want
//my code to be able to pick up where I left off
e.printStackTrace();
logger.warn(e.getMessage());
}
catch (IOException e)
{
e.printStackTrace();
}
}
Here is the method that I want to keep checking if the directory exists. If the file is being written into and all of a sudden the directory goes down. I dont want to repeat the same information in the file I want it to continue to write from where it left off but I just cant figure out how to do that. thank you.
private void createBusFile(Bus<buses> aBusObject, CSVWriter writer) throws InterruptedException
{
//Get bus information here
for(Bus<buses> busStop : aBusObject.getBusStops())
{
busNumber = busStop.getBusNumber();
busArrivalTime = busStop.getBusArrivalTime();
busStop = busStop.getBusStop();
String[] busFields = {busNumber, busDate, busStop};
//If a file not found exception is thrown here I want it to keep checking if the directory exists. And pick up from where I left off
writer.writeNext(busFields);
}
}
}

My button can't open my class

Basically, the problem is I created an interface with Java Scene Builder. And from FXML button I wanted to open my class.
#FXML
public void pressButton(ActionEvent event) throws Exception {
Platform.runLater(() -> {
try{
new SerialChart().start(new Stage());
} catch (Exception e) {
e.printStackTrace();
}
});
}
#FXML
public void pressButton2(ActionEvent event) throws Exception {
Platform.runLater(() -> {
try {
new Main().start(new Stage());
} catch (Exception e) {
e.printStackTrace();
}
});
}
And my Main can be open, but my SerialChart can't be opened. It says "The constructor SerialChart() is undefined". So here is the problem I think
public SerialChart(String title) {
super(title);
I think this is the problem why I can't open. Please help me... I can show you the whole code if you need.
Like Jim Garrisson said, your constructor that you call takes no arguments, but your defined one does (String title). This means you need to pass in a String argument (Even a blank one like "" will work) when you call it in the Button function.
new SerialChart("Some Title").start(new Stage()); //should be your call in the Button function.
so this is the answer I figured out SO HAPPY
public void pressButton(ActionEvent event) throws Exception {
Platform.runLater(() -> {
try{
SerialChart serialChartDemo = new SerialChart("Clean Energy Data Real time graph");
serialChartDemo.pack();
RefineryUtilities.centerFrameOnScreen(serialChartDemo);
serialChartDemo.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
});
}

How to save a whole stack/list/array (some sort of multiple data structure) to a text document

I'm trying to create a rudimentary history system for a web browser I'm designing, unfortunately, I can only find ways to either store 1 web address for a history, or not at all, the fileWriter and fileOutputStream seem to limit to one single item per write, which would overwrite the previous if I tried to output one at a time.
I would appreciate it if people could either suggest ways to store an entire list of strings in an external txt doc, bonus points if you can retain an order to them
request for code:
private void loadWebPage(String userInput) {
if (stackTest == true) {
forwardStack.push(urlBox.getText());
stackTest = false;
} else {
backStack.push(urlBox.getText());
}
try {
createHistory(urlBox.getText());
// displays the content of a html link in the web window, as per
// user input
webWindow.setPage(userInput);
// sets the text in the urlbox to the user input so they can check
// at any time what page they are on
urlBox.setText(userInput);
} catch (Exception e) {
// if user enters a bad url then produce error
try {
File file = new File(userInput);
webWindow.setPage(file.toURI().toURL());
} catch (Exception e1) {
System.out.println("Error 001: Bad URL");
}
}
}
private void createHistory(String webAddress) {
JMenuItem button = new JMenuItem(webAddress);
history.add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent histPress) {
loadWebPage(webAddress);
historyStack.push(webAddress);
try {
FileWriter writer = new FileWriter(histPath, false);
writer.write(historyStack);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
private void recoverHistory() {
//this will read from the txt doc and create a
//history based on past uses of the browser
}
FileWriter will not store any data construct and will overwrite each value if done using string and forLoop
I hope someone knows the answer

Why my "Save" button doesn't work?

I have one of the biggest problem in my program. I've created Save button, but it saves if the .txt file is new (Then that button does "SaveAs" function). But when I open file, then type something and trying to save and it's not saving :S. Can anyone help me?
Here's the code:
fileSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(currentFile == null) {
int saveResult = fileSelect.showSaveDialog(null);
if(saveResult == fileSelect.APPROVE_OPTION) {
saveFile(fileSelect.getSelectedFile(), field.getText());
} else {
saveFile(currentFile, field.getText());
}
}
}
});
public void saveFile(File file, String contents) {
BufferedWriter writer = null;
String filePath = file.getPath();
if(!filePath.endsWith(".txt")) {
filePath += ".txt";
}
try {
writer = new BufferedWriter(new FileWriter(filePath));
writer.write(contents);
writer.close();
field.setText(contents);
setTitle("Editex - " + filePath);
currentFile = file;
} catch (Exception e) {
}
}
You aren't handling when currentFile != null, which is what I am assuming is the case when you are trying to save a file that already has a Filename.
Do something like this:
if(currentFile == null) {
// Handle if new file
} else {
// Handle an existing file
}
Move
saveFile(currentFile, field.getText());
into the else part of the above if else.
At the moment you have it within the if(currentFile == null), and this isn't the correct place as you are calling saveFile(null, field.getText()) here.
Also
catch(Exception e) {
}
is bad, never swallow an exception and do nothing with it, you will never know if an exception happens or not, just nothing will happen.

Categories

Resources