Java Null Pointer When clicking JButton(Eclipse) - java

Here is my code. I am trying to make a basic text editor just to try out file writing and reading along with JPanels and such. My current issue is that users are required to input the full file path of the file and that can get quite frustrating. So I made a button that allows the user to have preset file path settings. When you click on the 'File Path Settings' button, there is a window that pops up allowing you to set the settings. (A file browsing button will be implemented later I just wanted to do this for fun first.)
public class EventListeners {
String textAreaValue;
String filePath;
String rememberedPath;
String rememberedPathDirectory;
//Global components
JTextField fileName,saveFilePath,filePathSaveDirectory,savedFilePath;
JButton save,help,savePath;
//JTextArea text;
public EventListeners(){
window();
}
public void window(){
JFrame window = new JFrame();
window.setVisible(true);
window.setSize(650,500);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
JButton saveFilePath = new JButton("File Path Save Settings");
JTextArea ltext = new JTextArea(10,50);
JLabel filler = new JLabel(" ");
JLabel lfileName = new JLabel("File Path(If error click help)");
JLabel lsaveFilePath = new JLabel("Save Path");
fileName = new JTextField(30);
save = new JButton("Save File");
help = new JButton("Help");
panel.add(lfileName);
panel.add(fileName);
panel.add(save);
panel.add(help);
panel.add(ltext);
panel.add(filler);
window.add(panel);
saveFilePath.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//JOptionPane.showMessageDialog(null,"Hello world!");
JFrame windowB = new JFrame();
int windows = 2;
windowB.setVisible(true);
windowB.setSize(500,500);
windowB.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panelB = new JPanel();
JLabel lFilePathSaveDirectory = new JLabel("Directory where the file path settings will be stored");
filePathSaveDirectory = new JTextField(20);
JLabel lsavedFilePath = new JLabel("The full file path or part you want stored.");
savedFilePath = new JTextField(20);
savePath = new JButton("Save Settings");
panelB.add(lFilePathSaveDirectory);
panelB.add(filePathSaveDirectory);
panelB.add(lsavedFilePath);
panelB.add(savedFilePath);
panelB.add(savePath);
windowB.add(panelB);
}
});
save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textAreaValue = ltext.getText();
filePath = fileName.getText();
try {
FileWriter fw = new FileWriter(filePath);
PrintWriter pw = new PrintWriter(fw);
pw.println(textAreaValue);
pw.close();
JOptionPane.showMessageDialog(panel, "File Written!","Success!",JOptionPane.PLAIN_MESSAGE);
} catch(IOException x) {
JOptionPane.showMessageDialog(panel, "Error in writing file. \n\n Try Checking the file path or making sure the directory in which you are saving the file exists. \n\n Keep Calm and Love Beavers","Error",JOptionPane.ERROR_MESSAGE);
}
}
});
help.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(panel, " ***The file name must be the full file path.***\n\n-=-=-=-=-=-=-=-=-=(MAC)=-=-=-=-=-=-=-=-=-\n\n Example: /Users/Cheese/Documents/FileName.txt\n\n\n-=-=-=-=-=-=-=-=(WINDOWS)=-=-=-=-=-=-=-=-\n\n *Note that 2 back slashes must be used* \n\nC:\\user\\docs\\example.txt", "Help",JOptionPane.PLAIN_MESSAGE);
}
});
panel.add(saveFilePath);
window.add(panel);
saveFilePath.setSize(20,100);
savePath.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
rememberedPathDirectory = filePathSaveDirectory.getText();
rememberedPath = savedFilePath.getText();
try {
FileWriter fw = new FileWriter(rememberedPathDirectory+"filePathSettings.txt");
PrintWriter pw = new PrintWriter(fw);
pw.println(rememberedPath);
pw.close();
JOptionPane.showMessageDialog(panel, "File Written!","Success!",JOptionPane.PLAIN_MESSAGE);
} catch(IOException x) {
JOptionPane.showMessageDialog(panel, "Error in writing file. \n\n Try Checking the file path or making sure the directory in which you are saving the file exists. \n\n Keep Calm and Love Beavers","Error",JOptionPane.ERROR_MESSAGE);
}
JOptionPane.showMessageDialog(panel, "The application will close. Anythings not saved will be deleted", "Alert",JOptionPane.WARNING_MESSAGE);
}
});
}
public static void main(String[] args) {
new EventListeners();
}
}

main problem is you are creating variable with same name inside the constructer, you already define as instance .then your instance variable keep uninitialized/null.
for example
you have declare instance variable
JButton save, help, savePath, saveFilePath;
inside constructor you are creating another local jbutton and initialize it so instance variable is null.
so instead of creating new one you should initialize instance field.
JButton saveFilePath = new JButton("File Path Save Settings"); // problem
saveFilePath = new JButton("File Path Save Settings"); // correct way
but there is a another problem ..you have declare saveFilePath instance field as a jtextfield and you have created a saveFilePath button inside the constructor .i think it may be a button not a textfield.
also you are initializing some variables inside saveFilePath.addActionListener(new ActionListener() { method but you are adding actionlistners to them before saveFilePath action fired .you have to add actionlistners after you initialized a component.
also you should call repaint() at last after you add all the component to a frame..
try to run this code
import javax.swing.*;
import java.awt.event.*;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class EventListeners {
String textAreaValue;
String filePath;
String rememberedPath;
String rememberedPathDirectory;
//Global components
JTextField fileName, filePathSaveDirectory, savedFilePath;
JButton save, help, savePath, saveFilePath;
//JTextArea text;
public EventListeners() {
window();
}
public void window() {
JFrame window = new JFrame();
window.setSize(650, 500);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
saveFilePath = new JButton("File Path Save Settings");
JTextArea ltext = new JTextArea(10, 50);
JLabel filler = new JLabel(" ");
JLabel lfileName = new JLabel("File Path(If error click help)");
JLabel lsaveFilePath = new JLabel("Save Path");
fileName = new JTextField(30);
save = new JButton("Save File");
help = new JButton("Help");
panel.add(lfileName);
panel.add(fileName);
panel.add(save);
panel.add(help);
panel.add(ltext);
panel.add(filler);
window.add(panel);
saveFilePath.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//JOptionPane.showMessageDialog(null,"Hello world!");
JFrame windowB = new JFrame();
int windows = 2;
windowB.setVisible(true);
windowB.setSize(500, 500);
windowB.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panelB = new JPanel();
JLabel lFilePathSaveDirectory = new JLabel("Directory where the file path settings will be stored");
filePathSaveDirectory = new JTextField(20);
JLabel lsavedFilePath = new JLabel("The full file path or part you want stored.");
savedFilePath = new JTextField(20);
savePath = new JButton("Save Settings");
panelB.add(lFilePathSaveDirectory);
panelB.add(filePathSaveDirectory);
panelB.add(lsavedFilePath);
panelB.add(savedFilePath);
panelB.add(savePath);
windowB.add(panelB);
System.out.println(savePath);
savePath.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
rememberedPathDirectory = filePathSaveDirectory.getText();
rememberedPath = savedFilePath.getText();
try {
FileWriter fw = new FileWriter(rememberedPathDirectory + "filePathSettings.txt");
PrintWriter pw = new PrintWriter(fw);
pw.println(rememberedPath);
pw.close();
JOptionPane.showMessageDialog(panel, "File Written!", "Success!", JOptionPane.PLAIN_MESSAGE);
} catch (IOException x) {
JOptionPane.showMessageDialog(panel, "Error in writing file. \n\n Try Checking the file path or making sure the directory in which you are saving the file exists. \n\n Keep Calm and Love Beavers", "Error", JOptionPane.ERROR_MESSAGE);
}
JOptionPane.showMessageDialog(panel, "The application will close. Anythings not saved will be deleted", "Alert", JOptionPane.WARNING_MESSAGE);
}
});
}
});
save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textAreaValue = ltext.getText();
filePath = fileName.getText();
try {
FileWriter fw = new FileWriter(filePath);
PrintWriter pw = new PrintWriter(fw);
pw.println(textAreaValue);
pw.close();
JOptionPane.showMessageDialog(panel, "File Written!", "Success!", JOptionPane.PLAIN_MESSAGE);
} catch (IOException x) {
JOptionPane.showMessageDialog(panel, "Error in writing file. \n\n Try Checking the file path or making sure the directory in which you are saving the file exists. \n\n Keep Calm and Love Beavers", "Error", JOptionPane.ERROR_MESSAGE);
}
}
});
help.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(panel, " ***The file name must be the full file path.***\n\n-=-=-=-=-=-=-=-=-=(MAC)=-=-=-=-=-=-=-=-=-\n\n Example: /Users/Cheese/Documents/FileName.txt\n\n\n-=-=-=-=-=-=-=-=(WINDOWS)=-=-=-=-=-=-=-=-\n\n *Note that 2 back slashes must be used* \n\nC:\\user\\docs\\example.txt", "Help", JOptionPane.PLAIN_MESSAGE);
}
});
panel.add(saveFilePath);
window.add(panel);
saveFilePath.setSize(20, 100);
window.setVisible(true);
}
public static void main(String[] args) {
new EventListeners();
}
}

You also may want to consider dependency injection. That is becoming the standard way of doing things in the industry. Instead of the constructor doing all the work of creating all the objects your class uses, or calling another method like window() to do all the work, you pass in all the specifications to the constructor. It might look something like
public EventListeners(JButton save, JButton help, JButton saveFilePath) {
this.save = save;
this.help = help;
this.saveFilePath = saveFilePath);
}
Of course, you could also use a dependency injection framework like Spring, but that might be a bit much if your application is small.

Related

How to draw image using FileDialog in Java

Need to display selected in FileDialog image, but thats somewhy didnt work. When i try to choose image it throws exception javax.imageio.IIOException: Can't create an ImageInputStream!
I think problem is in getDirectory() , but dont know how to fix.
public ImageShow() throws IOException {
super("Pictures");
setSize(1024,768);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
JPanel buttonPanel = new JPanel(new FlowLayout());
buttonOpen = new JButton("Open file");
buttonPanel.add(buttonOpen);
actions();
fileDialog();
add(buttonPanel);
image = ImageIO.read(new File(fd.getDirectory()));
imageLabel = new JLabel(new ImageIcon(image));
buttonPanel.add(imageLabel);
}
public void fileDialog() {
fd = new FileDialog(new JFrame(), "Choose file");
fd.setVisible(true);
}
public void actions() {
buttonOpen.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
fileDialog();
}
});
}
}
image = ImageIO.read(new File(fd.getDirectory()));
A directory is not an image! Try instead getFile() which:
Gets the selected file of this file dialog. If the user selected CANCEL, the returned file is null.
But as I said in comments..
Use the Swing based JFileChooser rather than the AWT based FileDialog.
And be sure to consult the avialable documentation when using methods.

Processing a file with JFileChooser

Hey guys I am running into an issue with my program. I am trying to get the program to only show text files, and once the user selects one, the file information should be displayed in a textbox in the GUI. I am getting this error:
FileChooserDemo3.java:66: error: unreported exception IOException; must be caught or declared to be thrown
while ((strLine = br.readLine()) != null) {
Why is this happening? I have a catch statement.. Thanks for any help!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Scanner;
import java.io.*;
class FileChooserDemo3{
JLabel jlab;
JButton jbtnShow;
JFileChooser jfc;
JTextArea jta;
JScrollPane scrollPane;
FileChooserDemo3() {
//create new JFrame container.
JFrame jfrm = new JFrame("JFileChooser Demo");
//Specify FlowLayout for layout manager
jfrm.setLayout(new FlowLayout());
//Give the frame initial size
jfrm.setSize(800,800);
//End program when user closes application
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create a label to show selected file
jlab=new JLabel();
//Create button to show dialog
jbtnShow = new JButton("Show File Chooser");
//create textarea with ability to textwrap (p889-891) and scroll (hint: Use JScrollPane)
JTextArea textInput = new JTextArea(20, 40);
textInput.setLineWrap(true);
JScrollPane scrollPane = new JScrollPane(textInput);
//Create file chooser starting at default directory
jfc=new JFileChooser();
//Show file chooser when show file chooser button pressed
jbtnShow.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent le) {
//Pass null for the parent. This centers the dialog on the screen.
int result = jfc.showOpenDialog(null);
if(result==JFileChooser.APPROVE_OPTION){
jlab.setText("Selected file is: " + jfc.getSelectedFile().getName());
//Get selected file stored as a file.
try{
//Do file processing here
String strLine;
File selectedFile = jfc.getSelectedFile();
FileInputStream in = new FileInputStream(selectedFile);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
while ((strLine = br.readLine()) != null) {
textInput.append(strLine + "\n");
}
}
catch(FileNotFoundException e){
System.out.println("Exception");
}
}
else{
jlab.setText("No file selected.");
}
}
});
//add the show file chooser button and label to content pane
jfrm.add(jbtnShow);
jfrm.add(jlab);
//Display the frame
jfrm.setVisible(true);
}
public static void main(String[] args){
//Create GUI on the event dispatching thread.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new FileChooserDemo3();
}
});
}
}
You are catching FileNotFoundException, but you also need to catch IOException after your try {} block.
Programmatically, this is because readLine declares throws IOException. Translated, what it's saying is that even after the file is opened, it could still encounter a problem reading from the file.
Whats happening is exactly what it says is happening. "unreported exception IOException." Basically your catch statement is not catching all possible exceptions that can be thrown, change it to catch either IOException, or to make sure it catches every possible excepion, no matter what, make it catch Exception.

Java File Directory Issue

I am developing a java program which takes a students name and displays the name and date on a JTextPane. When the user presses exit, the program is supposed to automatically save the file in a specified directory inside a new folder created with the same name as the one the user provided for the student. Below is my code:
public class StudentRecorder extends JFrame implements ActionListener{
MyKeyListener listener;
public JTextPane page;
private JScrollPane scroll;
private JMenuBar menubar;
private AttributeSet aset;
public String name;
private JMenu menufile;
private JMenuItem exit;
StudentRecorder(){
super("Student Recorder");
init();
this.setSize(400, 400);
this.setLocation(400, 400);
this.setVisible(true);
}
void init(){
menubar = new JMenuBar();
name = JOptionPane.showInputDialog(this, "Enter Student's Name:\n(For locations of files to be preserved, "
+ "names\nare case-sensitive.)", "Student Name", JOptionPane.QUESTION_MESSAGE);
String timeStamp = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").format(Calendar.getInstance().getTime());
page = new JTextPane();
if (name.equals("")){
aset = StyleContext.getDefaultStyleContext().addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, Color.RED);
page.setCharacterAttributes(aset, false);
page.setText(timeStamp + "\n" + "(Student Name Not Typed In. You must manually save this file. File "
+ "wont be autosaved.)" + "\n\n");
}
else{
page.setText(timeStamp + "\n" + name + "\n\n");
}
//Declaration
menufile = new JMenu("File");
exit = new JMenuItem("Exit");
//Adding to JMenuBar
menubar.add(menufile);
menufile.add(exit);
//Add ActionListener
exit.addActionListener(this);
//Page characteristics
aset = StyleContext.getDefaultStyleContext().addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, Color.BLACK);
page.setCharacterAttributes(aset, false);
Font font = new Font("Arial", Font.PLAIN, 14);
page.setFont(font);
this.setJMenuBar(menubar);
scroll = new JScrollPane(page);
this.add(scroll);
scroll.createHorizontalScrollBar();
listener = new MyKeyListener();
page.addKeyListener(listener);
page.setFocusable(true);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == exit){
File f = new File("./Desktop/" + name);
try{
if(f.mkdir()){
System.out.println("Directory Created.");
System.exit(0);
}
else{
System.out.println("Directory Not Created.");
}
}catch(Exception e1){
e1.printStackTrace();
}
}
}
}
I am running into an issue in my program where the file doesn't save to the Directory with the name provided. It consistently pops up in the console 'Directory Not Created'. Can anyone please tell me how I can fix this problem? There are no other errors in my code preventing it from running.
Thanks in advance to all who reply.
The reason you are getting this problem is because you are trying to create a directory inside ./Desktop and you are running this from inside Documents which doesn't have a Desktop folder. To save it to Desktop you have to use an absolute path. Absolute paths start with a / on unix (mac and linux) and with C: on Windows:
File f = new File("/Users/yourname/Desktop/" + name);

How to Display the Contents of a text file in a TextArea

How do you display the contents of a text file in a TextArea when your using JFileChooser.
You have to read official Oracle's JTextArea tutorial
Especially method JTextArea.read(fileSelectedFromJFileChooser) , maybe right way in this case
Please have a look at Reading, Writing and Creating Files Tutorials
Here find one example program, for your help, though if the file to be read is long, then always take the help of SwingWorker :
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ReadFileExample
{
private BufferedReader input;
private String line;
private JFileChooser fc;
public ReadFileExample()
{
line = new String();
fc = new JFileChooser();
}
private void displayGUI()
{
final JFrame frame = new JFrame("Read File Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JTextArea tarea = new JTextArea(10, 10);
JButton readButton = new JButton("OPEN FILE");
readButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
int returnVal = fc.showOpenDialog(frame);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
//This is where a real application would open the file.
try
{
input = new BufferedReader(
new InputStreamReader(
new FileInputStream(
file)));
tarea.read(input, "READING FILE :-)");
}
catch(Exception e)
{
e.printStackTrace();
}
} else {
System.out.println("Operation is CANCELLED :(");
}
}
});
frame.getContentPane().add(tarea, BorderLayout.CENTER);
frame.getContentPane().add(readButton, BorderLayout.PAGE_END);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new ReadFileExample().displayGUI();
}
});
}
}
Your question is unclear, but I am assuming you want to add the JTextArea to the JFileChooser so that it can act like a file preview panel.
You can add a JTextArea to the JFileChooser by using the setAccessory() method.
This tutorial on JFileChooser shows how to do something similar where the accessory displays an image from the file rather than text from the file.
You will need to be careful to deal properly with files that don't contain text, or which are too large, or which cannot be opened due to permission, etc. It will take a good bit of effort to get it right.

How do i write to a text file using java?

I have been using the "Learning Java 2nd Edtion" book to try make my java application write my input to a text file called properties. I have manipulated the text book example into my own code but still having problems trying to get it to work. I think i may need to hook it up to my submit button but this wasnt mentioned within the chapter.
Basically im trying to store the information in the text file and then use that text file within another location to read all of the property details.
Here is my code for the AddProperty Page so far any advice would be greatly appreciated.
At the moment iv hit the wall.
/**
*
* #author Graeme
*/
package Login;
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.border.EmptyBorder;
public class AddProperty
{
public void AddProperty()
{
JFrame frame = new JFrame("AddPropertyFrame");
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// having to set sizes of components is rare, and often a sign
// of problems with layouts.
//frame.setSize(800,600);
JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20,20));
// make it big like the original
panel.setBorder(new EmptyBorder(100,20,100,20));
frame.add(panel);
//panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
JLabel HouseNumber = new JLabel("House Number/Name");
panel.add(HouseNumber);
JTextField HouseNumber1 = new JTextField(10);
panel.add(HouseNumber1);
JLabel HousePrice = new JLabel("House Price");
panel.add(HousePrice);
JTextField HousePrice1 = new JTextField(10);
panel.add(HousePrice1);
JLabel HouseType = new JLabel("House Type");
panel.add(HouseType);
JTextField HouseType1 = new JTextField(10);
panel.add(HouseType1);
JLabel Location = new JLabel("Location");
panel.add(Location);
JTextField Location1 = new JTextField(10);
panel.add(Location1);
JButton submit = new JButton("Submit");
panel.add(submit);
submit.addActionListener(new Action());
// tell the GUI to assume its natural (minimum) size.
frame.pack();
}
static class Action implements ActionListener{
#Override
public void actionPerformed (ActionEvent e)
{
// this should probably be a modal JDialog or JOptionPane.
JOptionPane.showMessageDialog(null, "You have successfully submitted a property.");
}
static class propertyList
{
public static void main (String args[]) throws Exception {
File properties = new File(args[0]);
if (!properties.exists() || !properties.canRead() ) {
System.out.println("Cant read " + properties);
return;
}
if (properties.isDirectory()){
String [] properties1 = properties.list();
for (int i=0; i< properties1.length; i++)
System.out.println();
}
else
try {
FileReader fr = new FileReader (properties);
BufferedReader in = new BufferedReader (fr);
String line;
while ((line = in.readLine())!= null)
System.out.println(line);
}
catch (FileNotFoundException e){
System.out.println("Not Able To Find File");
}
}
}
}
}
in your Action performed you are not stating anything, for example in your action performed you could add.
public void actionPerformed(ActionEvent e)
{
houseNumber2 = houseNumber1.getText();
housePrice2 = housePrice1.getText();
town1 = town.getText();
comboBoxType2 = comboBoxType1.getSelectedItem();
inputData = housenumber2 + "," + housePrice2 + "," + town1 + "," + comboBoxType2;
FileName.Filewritermethod(inputData);
frame.setVisible(false);
}
});
This would strings to take the values of your JTexFields and pass them onto a textfile provided you have a FileWriter Class
Your action listener is not doing anything much right now.
Add code to add property in the following method:
public void actionPerformed (ActionEvent e)
{
//add your code here
}

Categories