Getting String from inside an ActionListener
Hello,
I've had some problems lately with getting a String out of an ActionListener.
Code:
package MainProjekt;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import javax.swing.JFileChooser.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.nio.Buffer;
public class Main{
public static JTextArea textarea;
private static JMenuBar menuBar = new JMenuBar();
public static JFrame frame;
private static JFileChooser chooser;
private static JFileChooser chooser2;
private static JFileChooser chooser3;
private static String fn;
private static String fl;
public static void main(String args[])
{
fn = "unnamed";
fl = "C:/Users/Kristoffer/Desktop/";
frame = new JFrame("SpitWriter - " + fn + ".txt");
JPanel panel = new JPanel();
textarea = new JTextArea(32,50);
JPanel panel2 = new JPanel();
textarea.setDragEnabled(false);
textarea.setLineWrap(true); // Makes it so it CANNOT be expanded to in width
JScrollPane scroll = new JScrollPane(textarea, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
frame.setVisible(true);
frame.setSize(600,600);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setJMenuBar(menuBar); // Adds the menu bar to the frame
frame.add(panel);
frame.add(panel2);
panel2.add(scroll); // Adds the scroll and the textarea at the same time
JMenu filemenu = new JMenu("File"); // Add a menu that says "File"
JMenu editmenu = new JMenu("Edit"); // Same as above just "Edit"
menuBar.add(filemenu); // Add the categories to the menu bar
menuBar.add(editmenu);
// Make actions for each menu bar
JMenuItem newAction = new JMenuItem("New");
JMenuItem openAction = new JMenuItem("Open");
JMenuItem saveAction = new JMenuItem("Save");
JMenuItem saveasAction = new JMenuItem("Save As");
JMenuItem exitAction = new JMenuItem("Exit");
JMenuItem cutAction = new JMenuItem("Cut");
JMenuItem copyAction = new JMenuItem("Copy");
JMenuItem pasteAction = new JMenuItem("Paste");
// Make a checkbox option
JCheckBoxMenuItem checkAction = new JCheckBoxMenuItem("Check Action"); // Make a pick(something) option
JRadioButtonMenuItem radioAction = new JRadioButtonMenuItem("Radio Button 1");
ButtonGroup bg = new ButtonGroup(); // Make a button group
bg.add(radioAction); // Add the radioAction to the group(pretty pointless since there's only 1
filemenu.add(newAction); // Add the different actions to each menu.
filemenu.add(openAction);
filemenu.add(saveAction);
filemenu.add(saveasAction);
filemenu.add(checkAction);
filemenu.addSeparator(); // Add an separator
filemenu.add(exitAction);
editmenu.add(cutAction);
editmenu.add(copyAction);
editmenu.add(pasteAction);
editmenu.addSeparator();
editmenu.add(radioAction);
saveAction.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String lnl = new String();
String fulltext = textarea.getText();
if (fn == "unnamed")
{
chooser = new JFileChooser();
chooser.addChoosableFileFilter(new txtSaveFilter());
chooser.addChoosableFileFilter(new batSaveFilter());
chooser.addChoosableFileFilter(new javaSaveFilter());
int rVal = chooser.showSaveDialog(null);
String fn = chooser.getSelectedFile().getName();
String fl = chooser.getCurrentDirectory().toString();
if (rVal == JFileChooser.APPROVE_OPTION)
{
String ex = "";
String Extension = chooser.getFileFilter().getDescription();
if (Extension.equals("Text (*.txt)"))
{
ex = ".txt";
}
else if (Extension.equals("Batch (*.bat)"))
{
ex = ".bat";
}
else if (Extension.equals("Java (*.java)"))
{
ex = ".java";
}
else
{
ex = ".txt";
}
try{
BufferedWriter out = new BufferedWriter(new FileWriter(fl + "/" + fn + ex));
out.write(fulltext);
out.close();
frame.setTitle("SpitWriter - " + fn + ex);
} catch (IOException i){}
}
}
else
{
String fn = fnB;
String fl = flB;
String ex = "";
String Extension = chooser2.getFileFilter().getDescription();
if (Extension.equals("Text (*.txt)"))
{
ex = ".txt";
}
else if (Extension.equals("Batch (*.bat)"))
{
ex = ".bat";
}
else if (Extension.equals("Java (*.java)"))
{
ex = ".java";
}
else
{
ex = ".txt";
}
try
{
BufferedWriter out = new BufferedWriter(new FileWriter(fl + "/" + fn + ex));
out.write(fulltext);
out.close();
} catch (IOException m){}
}
}
});
saveasAction.addActionListener(new ActionListener(){ // Make an ActionListener for the "save" Menu item
public void actionPerformed(ActionEvent i) {
String fulltext = textarea.getText(); // Get the text written
chooser2 = new JFileChooser(); // Makes a file chooser
chooser2.addChoosableFileFilter(new txtSaveFilter()); // Makes 3 FileFilters
chooser2.addChoosableFileFilter(new batSaveFilter());
chooser2.addChoosableFileFilter(new javaSaveFilter());
int rVal = chooser2.showSaveDialog(null); // Makes the file chooser show
if (rVal == JFileChooser.APPROVE_OPTION) // If you click save this will happen
{
String fn = chooser2.getSelectedFile().getName(); // Gets the filename written
String fl = chooser2.getCurrentDirectory().toString();
String fnB = fn;
String flB = fl;
String ex = ""; // Ex string
String Extension = chooser2.getFileFilter().getDescription(); // Extension string which gets the description of the current FileFilter
if (Extension.equals("Text (*.txt)")) // If the description of the current FileFilter = "*.txt, *.TXT"
{
ex = ".txt"; // It will chance the ex to the extension ".txt"
}
else if (Extension.equals("Batch (*.bat)")) // Same here just with bat
{
ex = ".bat";
}
else if (Extension.equals("Java (*.java)")) // Same here just with bat
{
ex = ".java";
}
else
{
ex = ".txt";
}
try{ // Write to a file
BufferedWriter out = new BufferedWriter(new FileWriter(fl + "/" + fn + ex));
out.write(fulltext);
out.close();
frame.setTitle("SpitWriter - " + fn + ex);
} catch (IOException e){}
}
}
});
openAction.addActionListener(new ActionListener() { // Makes the open file chooser
public void actionPerformed(ActionEvent e) {
chooser3 = new JFileChooser();
chooser3.setMultiSelectionEnabled(false);
chooser3.addChoosableFileFilter(new txtSaveFilter());
chooser3.addChoosableFileFilter(new batSaveFilter());
chooser3.addChoosableFileFilter(new javaSaveFilter());
int rVal = chooser3.showOpenDialog(null);
if (rVal == JFileChooser.APPROVE_OPTION)
{
String fl = chooser3.getCurrentDirectory().toString();
String fn = chooser3.getSelectedFile().getName();
try
{
FileInputStream fstream = new FileInputStream(fl + "/" + fn); // Prepares for it to read the file
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) // Reads each line
{
textarea.append(strLine+"\n"); // Adds the line to the text
}
in.close();
} catch (Exception k)
{
System.err.println("Error: " + k.getMessage());
}
frame.setTitle("SpitWriter - " + fn);
}
}
});
newAction.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textarea.setText("");
frame.setTitle("SpitWriter - " + fn + ".txt");
}
});
}
}
class txtSaveFilter extends FileFilter // This is the FileFilter for .txt
{
public boolean accept(File f) // Standard for FileFilters
{
if (f.isDirectory()) // Same here
{
return false; // Same
}
String s = f.getName(); // Gets the name and stores it in a string
return s.endsWith(".txt")||s.endsWith(".TXT");
}
public String getDescription() // Makes the description for the string
{
return "Text (*.txt)"; // "*.txt, *.TXT"
}
}
class batSaveFilter extends FileFilter // Same as above just with the BATCH file
{
public boolean accept(File f)
{
if (f.isDirectory())
{
return false;
}
String s = f.getName().toLowerCase();
return s.endsWith(".bat");
}
public String getDescription()
{
return "Batch (*.bat)";
}
}
class javaSaveFilter extends FileFilter
{
public boolean accept(File f)
{
if (f.isDirectory())
{
return false;
}
String s = f.getName().toLowerCase();
return s.endsWith(".java");
}
public String getDescription()
{
return "Java (*.java)";
}
}
If you go down to saveAction.AddActionListener
I'm trying to make it so that, when you click the dropdown menu "save" it will check weather it's a new(unnamed) file or if it's a file with an actual name. If it has a name, i want it to get that name, and it's location(directory) so i can make it just save without the JFileChooser window popping up. But i have a problem getting the fn(filename) and fl into the "else"
EDIT: Maybe you could make it store the Filename after you have either used "Save as" or "Open". But how?
And when pressing the "Cancel" button after either going into, "Open", "Save" or "Save as" it brings me an error, yet i can still run the program.
Re: Getting String from inside an ActionListener
Do you really think, we will bother reading such a huge code?
Please provide SSCCE
Re: Getting String from inside an ActionListener
Quote:
if (fn == "unnamed")
Use the equals method when comparing the contents of String objects. The == is for comparing primitives or the values of references.
Quote:
it brings me an error,
Please post the full text of the error message here.
Re: Getting String from inside an ActionListener
Nevermind,
Fixed it myself.
Re: Getting String from inside an ActionListener
That's the purpose of the forum: To help you fix your problems.