JAVA calling methods from other classes

Associate
Joined
19 Jul 2006
Posts
1,847
I have a few classes with in my package, with help from others on here

Code:
package gmailcsvapp;

import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Random;

public class PasswordGenerator {

	private CSVParser user;
	private CSVParser pass;

	public  PasswordGenerator()
	{
		try {
			user = new CSVParser("export.csv");
			pass = new CSVParser("passwordlist.txt");
		} catch (FileNotFoundException e) {
			System.out.println(e.getMessage());
		} catch (EmptyFileException e) {
			System.out.println(e.getMessage());
		}
                generateFirstnames();
                generateLastnames();
		generateUsernames();
		generatePasswords();

		try {
			user.toFile("exported.csv");
		} catch (FileNotFoundException e) {
			System.out.println(e.getMessage());
		}
	}

	public void generateUsernames()
	{
		for (int i = 0; i < user.getRowCount(); i++)
		{
			String[] row = user.getRow(i);
			String[] newRow = Arrays.copyOfRange(row, 1, row.length);
			String username = row[0].substring(0,1) + "." + row[1];
			newRow[0] = username.toLowerCase();
			user.setRow(i, newRow);
		}
	}

        public void generateFirstnames()
        {
            for (int i = 0; i <user.getRowCount(); i++)
            {
                String[] row =user.getRow(i);
                String[] newRow = Arrays.copyOfRange(row,1,row.length);
                String firstname = row[0];
                user.appendToRow(i,firstname);
            }
        }

        public void generateLastnames()
        {
            for (int i = 0; i <user.getRowCount(); i++)
            {
                String[] row =user.getRow(i);
                String[] newRow = Arrays.copyOfRange(row,1,row.length);
                String lastname = row[1];
                user.appendToRow(i,lastname);
            }
        }
      


	public void generatePasswords()
	{
		for (int i = 0; i < user.getRowCount(); i++)
		{
			user.appendToRow(i, getPassword());
		}
	}

	private String getPassword()
	{
		String[] passwords = pass.getCol(0);
		Random rand = new Random();
		String pass = passwords[rand.nextInt(passwords.length-1)];
		return pass.toLowerCase() + rand.nextInt(100);
	}

	public static void main(String[] args) {
		new Bodyitems();
//* this worked when this was new PasswordGenerator();


	}
}

and Bodyitems ( which is part of the GUI )
Code:
package gmailcsvapp;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
 *
 * 
 */
public class Bodyitems extends menuitems{

    public Bodyitems ()
    {
        super();
        JButton openButton = new JButton("Open Import");
        JLabel Importfilelb = new JLabel("Hello there");
        JLabel blank = new JLabel("Enter output file name");
        JTextField outputfiletxt = new JTextField("Outputfilename.csv");
        JButton outputButton = new JButton("Create New CSV");

        outputButton.addActionListener(new outputWatcher());



        Container cp = getContentPane();
        cp.setLayout(new GridLayout(3, 2));
	cp.add(openButton);
        cp.add(Importfilelb);
        cp.add(blank);
        cp.add(outputfiletxt);
        cp.add(outputButton);
        setVisible(true);
    }


    private class outputWatcher implements ActionListener
    {

        public void actionPerformed (ActionEvent a)
        {
             new PasswordGenerator();
        }
    }



}

Im trying to get it so that the text in the output file becomes the name of the exported.csv file

And i want to have some kind of way of navigating to the file to get the name of the import file using filechooser



TIA
 
Last edited:

fez

fez

Caporegime
Joined
22 Aug 2008
Posts
25,023
Location
Tunbridge Wells
It looks to me like you are refencing PasswordGenerator in a static context when the method or class is not static.

Try PasswordGenerator p = new Passwordgenerator(); instead of the last line there.

Are you using eclipse? The error handling usually gives you a good idea of the error.

If a class extends a parent class then the methods and constructor and any protected variables of the parent become available to overload and overwrite. From the code above you havnt got a sub class (child) of PasswordGenerator and Passwordgenerator does not extend any other class.
 
Soldato
Joined
9 May 2005
Posts
4,524
Location
Nottingham
Take a look at this, it is one approach to doing what you want.

The GUI is now the main class and it creates an instance on the Password Generator so that you can access its methods whenever you need. I have just bundled all of work of the constructor into a method called exec() but there is no reason you couldn't individually call the methods from the Bodyitems class (except user.toFile() which you would need to add a method to make it visible). You could take it further such as making the PasswordGenerator constructor accept parameters for the filenames and then use a textbox or filechooser on the GUI to specify them.

Code:
package gmailcsvapp;

import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Random;

public class PasswordGenerator {

  private CSVParser user;
  private CSVParser pass;

  public  PasswordGenerator()
  {
    try {
      user = new CSVParser("export.csv");
      pass = new CSVParser("passwordlist.txt");
    } catch (FileNotFoundException e) {
      System.out.println(e.getMessage());
    } catch (EmptyFileException e) {
      System.out.println(e.getMessage());
    }

    [COLOR="Red"]// <Removed 9 lines>[/COLOR]

  }

  [COLOR="Red"]public void exec()
  {
    generateFirstnames();
    generateLastnames();
    generateUsernames();
    generatePasswords();

    try {
      user.toFile("exported.csv");
    } catch (FileNotFoundException e) {
      System.out.println(e.getMessage());
    }
  }[/COLOR]

  public void generateUsernames()
  {
    for (int i = 0; i < user.getRowCount(); i++)
    {
      String[] row = user.getRow(i);
      String[] newRow = Arrays.copyOfRange(row, 1, row.length);
      String username = row[0].substring(0,1) + "." + row[1];
      newRow[0] = username.toLowerCase();
      user.setRow(i, newRow);
    }
  }

  public void generateFirstnames()
  {
    for (int i = 0; i <user.getRowCount(); i++)
    {
      String[] row =user.getRow(i);
      String[] newRow = Arrays.copyOfRange(row,1,row.length);
      String firstname = row[0];
      user.appendToRow(i,firstname);
    }
  }

  public void generateLastnames()
  {
    for (int i = 0; i <user.getRowCount(); i++)
    {
      String[] row =user.getRow(i);
      String[] newRow = Arrays.copyOfRange(row,1,row.length);
      String lastname = row[1];
      user.appendToRow(i,lastname);
    }
  }

  public void generatePasswords()
  {
    for (int i = 0; i < user.getRowCount(); i++)
    {
      user.appendToRow(i, getPassword());
    }
  }

  private String getPassword()
  {
    String[] passwords = pass.getCol(0);
    Random rand = new Random();
    String pass = passwords[rand.nextInt(passwords.length-1)];
    return pass.toLowerCase() + rand.nextInt(100);
  }

  [COLOR="Red"]// Removed main() method[/COLOR]

}

Code:
package gmailcsvapp;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/**
 *
 * 
 */
public class Bodyitems extends menuitems{

  [COLOR="Red"]private PasswordGenerator gen;[/COLOR]

  public Bodyitems ()
  {
    [COLOR="Red"]gen = new PasswordGenerator();[/COLOR]

    super();
    JButton openButton = new JButton("Open Import");
    JLabel Importfilelb = new JLabel("Hello there");
    JLabel blank = new JLabel("Enter output file name");
    JTextField outputfiletxt = new JTextField("Outputfilename.csv");
    JButton outputButton = new JButton("Create New CSV");

    outputButton.addActionListener(new outputWatcher());

    Container cp = getContentPane();
    cp.setLayout(new GridLayout(3, 2));
    cp.add(openButton);
    cp.add(Importfilelb);
    cp.add(blank);
    cp.add(outputfiletxt);
    cp.add(outputButton);
    setVisible(true);
  }

  private class outputWatcher implements ActionListener
  {
    public void actionPerformed (ActionEvent a)
    {
      [COLOR="Red"]gen.exec();[/COLOR]
    }
  }
  
  [COLOR="Red"]public static void main(String[] args]
  {
    new Bodyitems();
  }[/COLOR]
}
 
Last edited:
Associate
OP
Joined
19 Jul 2006
Posts
1,847
Thanks both im using Netbeans. I'm still really new to this. so not sure what using a none static method means

So just to get this clear in my head were creating an new instance of PasswordGenerator when the program starts. That loads the password file and the import file ?
Then when the button is pressed that is when the following is run
Code:
generateFirstnames();
    generateLastnames();
    generateUsernames();
    generatePasswords();

    try {
      user.toFile("exported.csv");
    } catch (FileNotFoundException e) {
      System.out.println(e.getMessage());
    }
  }

Will this not make it hard to change the imported file name that will be generated from the bodyitems class.

I take it to update the exported.csv file. i would use something like
Code:
public String getexportfile()
	{
		return outputfiletxt.getText() ;
	}

which brings up a cannot find symbol error?
 
Last edited:
Soldato
Joined
9 May 2005
Posts
4,524
Location
Nottingham
Then when the button is pressed that is when the following is run
Code:
    generateFirstnames();
    generateLastnames();
    generateUsernames();
    generatePasswords();

    try {
      user.toFile("exported.csv");
    } catch (FileNotFoundException e) {
      System.out.println(e.getMessage());
    }
  }
Yes, but I did mention that you might want to do it differently as it doesn't let you change the hard coded filenames. Something a bit more flexible is:

Code:
package gmailcsvapp;

import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Random;

public class PasswordGenerator {

  private CSVParser user;
  private CSVParser pass;

[COLOR="Red"]  public PasswordGenerator(String [B]inputFile[/B], String [B]passwordFile[/B])
  {
    try {
      user = new CSVParser([B]inputFile[/B]);
      pass = new CSVParser([B]passwordFile[/B]);
    } catch (FileNotFoundException e) {
      System.out.println(e.getMessage());
    } catch (EmptyFileException e) {
      System.out.println(e.getMessage());
    }

    generateFirstnames();
    generateLastnames();
    generateUsernames();
    generatePasswords();
  }[/COLOR]

  [COLOR="Red"]public void saveToFile(String [B]outputFile[/B])
  {
    try {
      user.toFile([B]outputFile[/B]);
    } catch (FileNotFoundException e) {
      System.out.println(e.getMessage());
    }  
  }[/COLOR]

  public void generateUsernames()
  {
    for (int i = 0; i < user.getRowCount(); i++)
    {
      String[] row = user.getRow(i);
      String[] newRow = Arrays.copyOfRange(row, 1, row.length);
      String username = row[0].substring(0, 1) + "." + row[1];
      newRow[0] = username.toLowerCase();
      user.setRow(i, newRow);
    }
  }

  public void generateFirstnames()
  {
    for (int i = 0; i < user.getRowCount(); i++)
    {
      String[] row = user.getRow(i);
      String[] newRow = Arrays.copyOfRange(row, 1, row.length);
      String firstname = row[0];
      user.appendToRow(i, firstname);
    }
  }

  public void generateLastnames()
  {
    for (int i = 0; i < user.getRowCount(); i++)
    {
      String[] row = user.getRow(i);
      String[] newRow = Arrays.copyOfRange(row, 1, row.length);
      String lastname = row[1];
      user.appendToRow(i, lastname);
    }
  }

  public void generatePasswords()
  {
    for (int i = 0; i < user.getRowCount(); i++)
    {
      user.appendToRow(i, getPassword());
    }
  }

  private String getPassword()
  {
    String[] passwords = pass.getCol(0);
    Random rand = new Random();
    String pass = passwords[rand.nextInt(passwords.length-1)];
    return pass.toLowerCase() + rand.nextInt(100);
  }

}

Code:
package gmailcsvapp;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/**
 *
 * 
 */
public class Bodyitems extends menuitems{

  private PasswordGenerator gen;

  public Bodyitems ()
  {
    super();
    JButton openButton = new JButton("Open Import");
    JLabel Importfilelb = new JLabel("Hello there");
    JLabel blank = new JLabel("Enter output file name");
    JTextField outputfiletxt = new JTextField("Outputfilename.csv");
    JButton outputButton = new JButton("Create New CSV");

    outputButton.addActionListener(new outputWatcher());

    Container cp = getContentPane();
    cp.setLayout(new GridLayout(3, 2));
    cp.add(openButton);
    cp.add(Importfilelb);
    cp.add(blank);
    cp.add(outputfiletxt);
    cp.add(outputButton);
    setVisible(true);
  }

  private class outputWatcher implements ActionListener
  {
    public void actionPerformed (ActionEvent a)
    {
      [COLOR="Red"]String in = inputFilenameField.getText();
      String pass = passwordListFilenameField.getText();
      gen = new PasswordGenerator(in, pass);

      // Note, the code below could go on a completely different button
      String out = outputFilenameField.getText();
      gen.saveToFile(out);[/COLOR]
    }
  }
  
  public static void main(String[] args]
  {
    new Bodyitems();
  }
}

Note that inputFilenameField, passwordListFilenameField and outputFilenameField are the names of 3 JTextField components that I have assumed exist on the GUI. They don't have to be JTextField components, you might decide to make use of a FileChooser or some other component.

In this code, an instance of PasswordGenerator is created when you click the button, it will gather the filenames of the input and output files from text fields on the GUI and pass them along to the PasswordGenerator constructor.

Hopefully the code is fairly straightforward, feel free to ask if you have any questions.
 
Associate
OP
Joined
19 Jul 2006
Posts
1,847
Thanks again Rob,

The compiler is not happy with
Code:
package gmailcsvapp;




import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/**
 *
 *
 */
public class Bodyitems extends menuitems{

  private PasswordGenerator gen;

  public Bodyitems ()
  {
    super();
    JButton openButton = new JButton("Open Import");
    JLabel Importfilelb = new JLabel("Hello there");
    JLabel blank = new JLabel("Enter output file name");
    JTextField outputFilenameField = new JTextField("Outputfilename.csv");
    JButton outputButton = new JButton("Create New CSV");

    outputButton.addActionListener(new outputWatcher());

    Container cp = getContentPane();
    cp.setLayout(new GridLayout(3, 2));
    cp.add(openButton);
    cp.add(Importfilelb);
    cp.add(blank);
    cp.add(outputFilenameField);
    cp.add(outputButton);
    setVisible(true);
  }

  private class outputWatcher implements ActionListener
  {
    public void actionPerformed (ActionEvent a)
    {
      String in = Bodyitems.cp.inputFilenameField.getText();
      gen = new PasswordGenerator(in);

      // Note, the code below could go on a completely different button
      String out = [COLOR="Red"]outputFilenameField[/COLOR].getText();
      gen.saveToFile(out);
    }
  }

  public static void main(String[] args)
  {
    new Bodyitems();
  }
}

cannot find symbol?

I modified it slightly as the password file is going to be static and not change.

I will want to implimet a file chooser to open a inputfile when the user clicks on the openButton
 
Soldato
Joined
9 May 2005
Posts
4,524
Location
Nottingham
outputFilenameField is not in scope when it is referenced in the action listener. You can reference it statically by doing Bodyitems.cp.outputFilenameField.getText(); but I would suggest that there are better ways to do this. There are discussions about how best to implement action listeners in Java, everyone seems to have a different solution, I prefer the anonymous inner class approach, you'll have to read up on that though.
 
Back
Top Bottom