Displaying Data from Text File on a Graph - java

Reading a .txt file using a file chooser and bufferedreader, I now need to display the data on a line graph. So the title from the text file will be at the top, with the axis labelled using the names given in the text file and the numbers plotted to make up the line graph. No idea where to begin with this as a complete beginner.

Since you use local classes, you can capture the text variable (your JTextArea) and use it in the action listener code:
class openaction implements ActionListener{
public void actionPerformed (ActionEvent e) {
JFileChooser chooser = new JFileChooser();
chooser.setDialogTitle("Open a Text File");
int result = chooser.showOpenDialog(null);
// ^^^ renamed this, so it doesn't hide 'text'
if (result == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
// Read in lines.
try(BufferedReader br = new BufferedReader(new FileReader(file))) {
// Append each line, plus a newline, to the text area.
br.lines().forEach(line -> text.append(line + System.lineSeparator()));
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}

Related

How to read multiple files one by one and display in the same text area in java swing?

I'm doing some coding for an assignment. I'm using java swing to do it. I need to know that how should change my code to display multiple files content in a text area.
I've tried some codes. I added one jButton and one jTextArea to read multiple files. I already know something about setMultiSelectionEnabled(true) and getSelectedFiles().
//This is my code inside the jButton
JFileChooser chooser = new JFileChooser();
chooser.setMultiSelectionEnabled(true);
chooser.showOpenDialog(null);
File files = chooser.getSelectedFiles();
String filename = files.getAbsolutePath();
try{
FileReader reader = new FileReader(filename);
BufferedReader br = new BufferedReader(reader);
jTextArea1.read(br, null);
br.close();
jTextArea1.requestFocus();
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
I can only get one file content into my text area yet. Please help me to develop this. Thank you!
If you want multiple files in a single text area, then you can't use the read(...) method.
Instead you will need to read each file line by line and the add the text to the text area using the append(...) method.
try this code:
JFileChooser chooser = new JFileChooser();
chooser.setMultiSelectionEnabled(true);
chooser.showOpenDialog(null);
File[] files = chooser.getSelectedFiles();
// String filename = files.getAbsolutePath();
for(File f:files){
FileReader reader = new FileReader(f);
BufferedReader br = new BufferedReader(reader);
while( (line = br.readLine()) != null ) {
jTextArea1.append(line);
}
br.close();
//jTextArea1.requestFocus();
}

Java swing Save and Save as functions with JFileChooser

I am writing a little app and would like to add the same handler for two buttons: Save and Save As. For save if the file exists it should not open the JFileChooser,just save the content, but with my current code it always opens the dialog. How do I do this? Here's my code
public void actionPerformed(ActionEvent e) {
JComponent source = (JComponent)e.getSource();
if (pathToFile.length()>0){
File file = new File(pathToFile);
if (file.exists()){
try(FileWriter fw = new FileWriter(file.getName() + ".txt", true)){
fw.write(area.getText());
}
catch(Exception ex){
System.out.println(ex.toString());
}
}
}
else{
if (fchoser.showSaveDialog(source.getParent())== JFileChooser.APPROVE_OPTION){
try(FileWriter fw = new FileWriter(fchoser.getSelectedFile()+".txt")){
fw.write(area.getText());
f.setTitle(fchoser.getSelectedFile().getPath());
pathToFile = fchoser.getSelectedFile().getPath();
}
catch(Exception ex){
}
}
}
UPDATE Added code to check if file exsists. It does and there is no exception but the additional text does not write.
Not related to your question but:
fw.write(area.getText());
Don't use the write method of a FileWriter. This will always write the text to the file using a "\n" as the line separator which may or may not be correct for the OS your code is running on.
Instead you can use the write(...) method of the JTextArea:
area.write(fw);
Then the proper line separator will be used.

How to save the text file in a path given by JFileChooser?

I need to save a text File which is already created in a particular path given by JFileChooser. What I do basically to save is:
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
int status = chooser.showSaveDialog(null);
if (status == JFileChooser.APPROVE_OPTION) {
System.out.print(chooser.getCurrentDirectory());
// Don't know how to do it
}
How to save the text file in a path given by JFileChooser?
You want to add the following after if statement:
File file = chooser.getSelectedFile();
FileWriter fw = new FileWriter(file);
fw.write(foo);
where foo is your content.
EDIT:
As you want to write a text file, I'd recommend the following:
PrintWriter out = new PrintWriter(file);
BufferedReader in = new BufferedReader(new FileReader(original));
while (true)
{
String line = in.nextLine();
if (line == null)
break;
out.println(line);
}
out.close();
where original is the file containing data you want to write.
create a new File object with the path and name for the file
File file = new File(String pathname)
Try this:
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
int status = chooser.showSaveDialog(null);
if (status == JFileChooser.APPROVE_OPTION) {
FileWriter out=new FileWriter(chooser.getSelectedFile());
try {
out.write("insert text file contents here");
}
finally {
out.close();
}
}
// ...
You'll need the filename you want to save under in addition to the directory provided by chooser.getCurrentDirectory(), but that should do what you need it to. Of course, you'll need to write the save method that actually writes to the stream, too, but that's up to you. :)
EDIT: There's a much method to use, chooser.getSelectedFile(), that should be used here, per another answer in the thread. Updated to use that method.
EDIT: Since OP specified the file being written is a text file, I've added code to write the contents of the file. Of course, you'll need to replace "insert text file contents here" with the actual file contents to write.

Reading a txt file in a Java GUI

All I want to do is display the entire contents of a txt file. How would I go about doing this? I'm assuming that I will set the text of a JLabel to be a string that contains the entire file, but how do I get the entire file into a string? Also, does the txt file go in the src folder in Eclipse?
This code to display the selected file contents in you Jtext area
static void readin(String fn, JTextComponent pane)
{
try
{
FileReader fr = new FileReader(fn);
pane.read(fr, null);
fr.close();
}
catch (IOException e)
{
System.err.println(e);
}
}
To choose the file
String cwd = System.getProperty("user.dir");
final JFileChooser jfc = new JFileChooser(cwd);
JButton filebutton = new JButton("Choose");
filebutton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (jfc.showOpenDialog(frame) !=JFileChooser.APPROVE_OPTION)
return;
File f = jfc.getSelectedFile();
readin(f.toString(), textpane);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
frame.setCursor(Cursor.
getPredefinedCursor(
Cursor.DEFAULT_CURSOR));
}
});
}
});
All I want to do is display the entire contents of a txt file. How
would I go about doing this? I'm assuming that I will set the text of
a JLabel to be a string that contains the entire file but how do I get the entire file into a string?
You would be better of using a JTextArea to do this. You can also look at the read() method.
does the txt file go in the src folder in Eclipse?
Nope. You can read files from any where. The tutorial on "Reading, Writing, and Creating Files" would be a good place to start
create text file in your project's working folder
read your text file line by line
store the line contents in stringBuilder variable
then append next line contents to stringBuilder variable
then assign the content of your StringBuilder variable to the JLabel's text property
But it is not good idea to store whole file's data into JLabel, use JTextArea or any other text containers.
Read your file like this:
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
line = br.readLine();
}
String everything = sb.toString();
} finally {
br.close();
}
now assign value of everything to JLabel or JTextArea
JLabel1.text=everything;
Use java.io to open a file stream.
Read content from file by lines or bytes.
Append content to StringBuilder or StringBuffer
Set StringBuilder or StringBuffer to JLable.text.
But I recommend using JTextArea..
You don't need to put this file in src folder.

Screenshot of gui, choose where to save question

I have a program that takes a screenshot of my gui. It automatically saves the .gif file to the eclipse project directory. What I would like is to have it asking a user where to save the image. Basically so the user can browse the file directory and choose the directory.
Here's the code I have:
public void actionPerformed(ActionEvent event) {
try{
String fileName = JOptionPane.showInputDialog(null, "Save file",
null, 1);
if (!fileName.toLowerCase().endsWith(".gif")){
JOptionPane.showMessageDialog(null, "Error: file name must end with \".gif\".",
null, 1);
}
else{
BufferedImage image = new BufferedImage(panel2.getSize().width,
panel2.getSize().height, BufferedImage.TYPE_INT_RGB);
panel2.paint(image.createGraphics());
ImageIO.write(image, "gif", new File(fileName));
JOptionPane.showMessageDialog(null, "Screen captured successfully.",
null, 1);
}
}
catch(Exception e){}
I would use a file chooser dialog instead of a JOptionPane. Here is a link for the tutorial.
Example:
First of all you have to declare JFileChooser object in your class and initialize it.
public Class FileChooserExample{
JFileChooser fc;
FileChooserExample(...){
fc = new JFileChooser();// as a parameter you can put path to initial directory to open
...
}
Now create another method:
private String getWhereToSave(){
int retVal = fc.showSaveDialog(..);
if(retVal == JFileChooser.APPROVE_OPTION){
File file = fc.getSelectedFile();
return file.getAbsolutePath();
}
return null;
}
This method returns to you the absolute path which user selected. retVal indicates which button was pressed (Save or Cancel). And if it was pressed Save then you handle the selected file.
Then you have this method you can incorporate this with your code. Instead of this line:
String fileName = JOptionPane.showInputDialog(null, "Save file", null, 1);
Write:
String fileName = getWhereToSave();

Categories