I want to create a simple stand-alone application that will take some input from user (some numbers and mathematical functions f(x,y...)) and write them to a file. Then with the help of this file I will run a command.
Basic ingredients that I need:
-- JTextArea for users input.
-- ButtonHandler/ActionListener and writing of the input to a (txt) file
-- ButtonHandler/ActionLister to execute a command
What is the best way to do it?
A current running code that I have (basically a toy) - which does not write anything, just executes - is:
import java.applet.*;
import java.lang.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Dialog;
import java.io.IOException;
import java.io.InputStream;
import java.io.*;
import java.util.*;
import java.io.BufferedWriter;
public class Runcommand3
{
public static void main(String[] args) throws FileNotFoundException, IOException
{
//JApplet applet = new JApplet();
//applet.init();
final JFrame frame = new JFrame("Change Backlight");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(null);
frame.add(panel);
JButton button = new JButton("Click me to Run");
button.setBounds(55,100,160,30);
panel.add(button);
frame.setSize(260,180);
frame.setVisible(true);
//This is an Action Listener which reacts to clicking on the button
button.addActionListener(new ButtonHandler());
}
}
class ButtonHandler implements ActionListener{
public void actionPerformed(ActionEvent event){
double value = Double.parseDouble(
JOptionPane.showInputDialog("please enter backlight value"));
//File theFile = new File("thisfile.txt");
//theFile.write(value);
String command = "xbacklight -set " + value;
try{Runtime run = Runtime.getRuntime();
Process pr = run.exec(command);}
catch(IOException t){t.printStackTrace();}
}
}
In the above example how can I write 'value' to a file? Then, how can I add more input (more textfields)? Can I do it in the same class or I need more? My confusion comes (mainly but not only) from the fact that inside the ButtonHandler class I can NOT define any other objects (ie, open and write files etc).
For your second question, you may like to consider having a JTextField on your JFrame for the user to enter lines into instead of a JOptionPane. It's just a simple text box, and you can add the box's contents to the file every time the button is pressed:
This is the way I would write to a file. I will let you convert this code into your GUI for practice. See more on BufferedWriter and FileWriter