Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 12 of 12

Thread: How to link two different class?

  1. #1
    Junior Member
    Join Date
    Mar 2009
    Posts
    28
    Thanks
    5
    Thanked 0 Times in 0 Posts

    Default How to link two different class?

    Hey all

    Basically i've got a question about how to put two classes together if that makes any sense

    The code below is for a GUI that uses a drop down menu.
    The menu allows the user to open a file and also gives the user the option of saving a file.
    This i shown in the code below:

    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.regex.*; 
    import javax.swing.*;
     
    public class Editor
        extends JFrame
        implements ActionListener {
      public static void main(String[] s) { new Editor(  ); }
     
      private JEditorPane textPane = new JEditorPane(  );
     
      public Editor(  ) {
        super("Editor v1.0");
        addWindowListener(new WindowAdapter(  ) {
          public void windowClosing(WindowEvent e) { System.exit(0); }
        });
        Container content = getContentPane(  );
        content.add(new JScrollPane(textPane), BorderLayout.CENTER);
        JMenu menu = new JMenu("File");
        menu.add(makeMenuItem("Open"));
        menu.add(makeMenuItem("Clean"));
        menu.add(makeMenuItem("Extract"));
        menu.add(makeMenuItem("Save"));
        menu.add(makeMenuItem("Quit"));
        JMenuBar menuBar = new JMenuBar(  );
        menuBar.add(menu);
        setJMenuBar(menuBar);
        setSize(300, 300);
        setLocation(200, 200);
        setVisible(true);
      }
     
      public void actionPerformed(ActionEvent e) {
        String command = e.getActionCommand(  );
        if (command.equals("Quit")) System.exit(0);
        else if (command.equals("Open")) loadFile(  );
        else if (command.equals("Save")) saveFile(  );
      }
     
      private void loadFile (  ) {
        JFileChooser chooser = new JFileChooser(  );
        int result = chooser.showOpenDialog(this);
        if (result == JFileChooser.CANCEL_OPTION) return;
        try {
          File file = chooser.getSelectedFile(  );
          java.net.URL url = file.toURL(  );
          textPane.setPage(url);
          	}
        catch (Exception e) {
          textPane.setText("Could not load file: " + e);
        }
      }
     
      private void saveFile(  ) {
        JFileChooser chooser = new JFileChooser(  );
        int result = chooser.showSaveDialog(this);
        // Save file data...
     
        if (result == JFileChooser.CANCEL_OPTION) return; // if user click on Save button
    	File file = chooser.getSelectedFile();
    	try {
             BufferedWriter bw = new BufferedWriter(new FileWriter(file));
             bw.write(textPane.getText());
             bw.close();
     
          	}
        catch (Exception e) {
             JOptionPane.showMessageDialog(
                this,
                e.getMessage(),
                "File Error",
                JOptionPane.ERROR_MESSAGE
             );
        } 
      } 
     
     
     
      private JMenuItem makeMenuItem( String name ) {
        JMenuItem m = new JMenuItem( name );
        m.addActionListener( this );
        return m;
      }
    }

    However i've also got another program that removes any whitespace from the xml tag headers contained within a file.

    The code for this is below:

    import java.util.regex.*;
    import java.io.*;
     
    public class regularexpressions{
      public static void main(String[] args) throws IOException{
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter file name: ");
        String filename = bf.readLine();
        File file = new File(filename);
        if(!filename.endsWith(".txt")){
          System.out.println("Usage: This is not a text file!");
          System.exit(0);
        }
        else if(!file.exists()){
          System.out.println("File not found!");
          System.exit(0);
        }
        FileInputStream fstream = new FileInputStream(filename);
        DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        Pattern p;
        Matcher m;
        String afterReplace = "";
        String strLine;
        String inputText = "";
        while ((strLine = br.readLine()) != null)
        if (strLine.contains("< d v d T i t l e >"))	
        	{
          System.out.println (strLine);
          inputText = strLine;
          p = Pattern.compile("\\s+");
          m = p.matcher(inputText);
          System.out.println(afterReplace);
          afterReplace = afterReplace + m.replaceAll("") + "\r\n";
        }
        else if (strLine.contains("< d v _ i d >"))	
        	{
          System.out.println (strLine);
          inputText = strLine;
          p = Pattern.compile("\\s+");
          m = p.matcher(inputText);
          System.out.println(afterReplace);
          afterReplace = afterReplace + m.replaceAll("") + "\r\n";
        }
        else if (strLine.contains("< / M e t a d a t a P r o v i d e r T i m e >"))	
        	{
          System.out.println (strLine);
          inputText = strLine;
          p = Pattern.compile("\\s+");
          m = p.matcher(inputText);
          System.out.println(afterReplace);
          afterReplace = afterReplace + m.replaceAll("") + "\r\n";
        }
        else if (strLine.contains("< a l b u m A r t i s t >"))	
        	{
          System.out.println (strLine);
          inputText = strLine;
          p = Pattern.compile("\\s+");
          m = p.matcher(inputText);
          System.out.println(afterReplace);
          afterReplace = afterReplace + m.replaceAll("") + "\r\n";
        }
        else if (strLine.contains("< a l b u m T i t l e >"))	
        	{
          System.out.println (strLine);
          inputText = strLine;
          p = Pattern.compile("\\s+");
          m = p.matcher(inputText);
          System.out.println(afterReplace);
          afterReplace = afterReplace + m.replaceAll("") + "\r\n";
        }
        FileWriter fstream1 = new FileWriter(filename);
        BufferedWriter out = new BufferedWriter(fstream1);
        out.write(afterReplace);
        in.close();
        out.close();
      }
    }

    In the gui there is also some other options for the user to choose, one of which is 'clean'.
    Basically what i want to do is link this program with the command 'clean' from the drop down menu in the gui if that makes sense.
    At the moment this program just allows the user to input and output to the console.
    Hoever i'm just curious how can i enable the Editor class to call on the regularexpressions class whenever the user selects clean form the drop down menu.
    I hope i've made some sense lol
    Any help is much appreciated.

    Thanks

    John


  2. #2
    Senile Half-Wit Freaky Chris's Avatar
    Join Date
    Mar 2009
    Posts
    834
    My Mood
    Cynical
    Thanks
    7
    Thanked 105 Times in 90 Posts

    Default Re: linking two different classes

    In your cleaning up class, you will need to get rid of public static void main(String[] args){} and replace it with a constructor to do the same thing, however you will want a method of passing the data to be cleaned to it rather than asking for commandline input of the file.

    Then when you want to call it you can do something like this,
    regularexpressions XMLClean = new regularexpression("Data to be cleaned);

    Or have a method called clean that reads in the data from a variable stored within the class and cleans it, then have a method of changing that variable so that the class is re useable.

    hope that all makes sense

    Regards,
    Chris

  3. #3
    Junior Member
    Join Date
    Mar 2009
    Posts
    28
    Thanks
    5
    Thanked 0 Times in 0 Posts

    Default Re: linking two different classes

    Quote Originally Posted by Freaky Chris View Post
    In your cleaning up class, you will need to get rid of public static void main(String[] args){} and replace it with a constructor to do the same thing, however you will want a method of passing the data to be cleaned to it rather than asking for commandline input of the file.

    Then when you want to call it you can do something like this,
    regularexpressions XMLClean = new regularexpression("Data to be cleaned);

    Or have a method called clean that reads in the data from a variable stored within the class and cleans it, then have a method of changing that variable so that the class is re useable.

    hope that all makes sense

    Regards,
    Chris
    Hey just wondering do you think it would be easier replacing the main method with a constructor or doing it all within the one class instead of having seperate classes?

    Thanks

    John

  4. #4
    mmm.. coffee JavaPF's Avatar
    Join Date
    May 2008
    Location
    United Kingdom
    Posts
    3,336
    My Mood
    Mellow
    Thanks
    258
    Thanked 294 Times in 227 Posts
    Blog Entries
    4

    Default Re: linking two different classes

    Hey John,

    It will probably take you the same amount of effort to do either one of these options.

    I think I would personally add the regularexpressions class as a method into the main Editor class.
    Please use [highlight=Java] code [/highlight] tags when posting your code.
    Forum Tip: Add to peoples reputation by clicking the button on their useful posts.

  5. #5
    mmm.. coffee JavaPF's Avatar
    Join Date
    May 2008
    Location
    United Kingdom
    Posts
    3,336
    My Mood
    Mellow
    Thanks
    258
    Thanked 294 Times in 227 Posts
    Blog Entries
    4

    Default Re: linking two different classes

    This should work John:

    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.regex.*;
    import javax.swing.*;
     
    public class Editor extends JFrame implements ActionListener {
     
        public static File file;
     
        public static void main(String[] s) {
            new Editor();
        }
     
        private JEditorPane textPane = new JEditorPane();
     
        public Editor() {
            super("Editor v1.0");
            addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
                }
            });
            Container content = getContentPane();
            content.add(new JScrollPane(textPane), BorderLayout.CENTER);
            JMenu menu = new JMenu("File");
            menu.add(makeMenuItem("Open"));
            menu.add(makeMenuItem("Clean"));
            menu.add(makeMenuItem("Extract"));
            menu.add(makeMenuItem("Save"));
            menu.add(makeMenuItem("Quit"));
            JMenuBar menuBar = new JMenuBar();
            menuBar.add(menu);
            setJMenuBar(menuBar);
            setSize(300, 300);
            setLocation(200, 200);
            setVisible(true);
        }
     
        public void actionPerformed(ActionEvent e) {
            String command = e.getActionCommand();
            if (command.equals("Quit"))
                System.exit(0);
            else if (command.equals("Open"))
                loadFile();
            else if (command.equals("Save"))
                saveFile();
            else if (command.equals("Clean"))
                try{
                regularexpressions();
                }catch(Exception fk){
                    System.out.println("Ouch, 'Clean' fell over! " + fk);
                }
        }
     
        private void loadFile() {
            JFileChooser chooser = new JFileChooser();
            int result = chooser.showOpenDialog(this);
            if (result == JFileChooser.CANCEL_OPTION)
                return;
            try {
                file = chooser.getSelectedFile();
                java.net.URL url = file.toURL();
                textPane.setPage(url);
            } catch (Exception e) {
                textPane.setText("Could not load file: " + e);
            }
        }
     
        private void saveFile() {
            JFileChooser chooser = new JFileChooser();
            int result = chooser.showSaveDialog(this);
            // Save file data...
     
            if (result == JFileChooser.CANCEL_OPTION)
                return; // if user click on Save button
            file = chooser.getSelectedFile();
            try {
                BufferedWriter bw = new BufferedWriter(new FileWriter(file));
                bw.write(textPane.getText());
                bw.close();
     
            } catch (Exception e) {
                JOptionPane.showMessageDialog(this, e.getMessage(), "File Error",
                        JOptionPane.ERROR_MESSAGE);
            }
        }
     
        private JMenuItem makeMenuItem(String name) {
            JMenuItem m = new JMenuItem(name);
            m.addActionListener(this);
            return m;
        }
     
        public static void regularexpressions() throws Exception {
     
            System.out.println("regularexpressions method called");
     
            FileInputStream fstream = new FileInputStream(file);
            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            Pattern p;
            Matcher m;
            String afterReplace = "";
            String strLine;
            String inputText = "";
            while ((strLine = br.readLine()) != null)
                if (strLine.contains("< d v d T i t l e >")) {
                    System.out.println(strLine);
                    inputText = strLine;
                    p = Pattern.compile("\\s+");
                    m = p.matcher(inputText);
                    System.out.println(afterReplace);
                    afterReplace = afterReplace + m.replaceAll("") + "\r\n";
                } else if (strLine.contains("< d v _ i d >")) {
                    System.out.println(strLine);
                    inputText = strLine;
                    p = Pattern.compile("\\s+");
                    m = p.matcher(inputText);
                    System.out.println(afterReplace);
                    afterReplace = afterReplace + m.replaceAll("") + "\r\n";
                } else if (strLine
                        .contains("< / M e t a d a t a P r o v i d e r T i m e >")) {
                    System.out.println(strLine);
                    inputText = strLine;
                    p = Pattern.compile("\\s+");
                    m = p.matcher(inputText);
                    System.out.println(afterReplace);
                    afterReplace = afterReplace + m.replaceAll("") + "\r\n";
                } else if (strLine.contains("< a l b u m A r t i s t >")) {
                    System.out.println(strLine);
                    inputText = strLine;
                    p = Pattern.compile("\\s+");
                    m = p.matcher(inputText);
                    System.out.println(afterReplace);
                    afterReplace = afterReplace + m.replaceAll("") + "\r\n";
                } else if (strLine.contains("< a l b u m T i t l e >")) {
                    System.out.println(strLine);
                    inputText = strLine;
                    p = Pattern.compile("\\s+");
                    m = p.matcher(inputText);
                    System.out.println(afterReplace);
                    afterReplace = afterReplace + m.replaceAll("") + "\r\n";
                }
            FileWriter fstream1 = new FileWriter(file);
            BufferedWriter out = new BufferedWriter(fstream1);
            out.write(afterReplace);
            in.close();
            out.close();
        }
    }
    Please use [highlight=Java] code [/highlight] tags when posting your code.
    Forum Tip: Add to peoples reputation by clicking the button on their useful posts.

  6. The Following User Says Thank You to JavaPF For This Useful Post:

    John (April 27th, 2009)

  7. #6
    Junior Member
    Join Date
    Mar 2009
    Posts
    28
    Thanks
    5
    Thanked 0 Times in 0 Posts

    Default Re: linking two different classes

    Quote Originally Posted by JavaPF View Post
    This should work John:

    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.regex.*;
    import javax.swing.*;
     
    public class Editor extends JFrame implements ActionListener {
     
        public static File file;
     
        public static void main(String[] s) {
            new Editor();
        }
     
        private JEditorPane textPane = new JEditorPane();
     
        public Editor() {
            super("Editor v1.0");
            addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
                }
            });
            Container content = getContentPane();
            content.add(new JScrollPane(textPane), BorderLayout.CENTER);
            JMenu menu = new JMenu("File");
            menu.add(makeMenuItem("Open"));
            menu.add(makeMenuItem("Clean"));
            menu.add(makeMenuItem("Extract"));
            menu.add(makeMenuItem("Save"));
            menu.add(makeMenuItem("Quit"));
            JMenuBar menuBar = new JMenuBar();
            menuBar.add(menu);
            setJMenuBar(menuBar);
            setSize(300, 300);
            setLocation(200, 200);
            setVisible(true);
        }
     
        public void actionPerformed(ActionEvent e) {
            String command = e.getActionCommand();
            if (command.equals("Quit"))
                System.exit(0);
            else if (command.equals("Open"))
                loadFile();
            else if (command.equals("Save"))
                saveFile();
            else if (command.equals("Clean"))
                try{
                regularexpressions();
                }catch(Exception fk){
                    System.out.println("Ouch, 'Clean' fell over! " + fk);
                }
        }
     
        private void loadFile() {
            JFileChooser chooser = new JFileChooser();
            int result = chooser.showOpenDialog(this);
            if (result == JFileChooser.CANCEL_OPTION)
                return;
            try {
                file = chooser.getSelectedFile();
                java.net.URL url = file.toURL();
                textPane.setPage(url);
            } catch (Exception e) {
                textPane.setText("Could not load file: " + e);
            }
        }
     
        private void saveFile() {
            JFileChooser chooser = new JFileChooser();
            int result = chooser.showSaveDialog(this);
            // Save file data...
     
            if (result == JFileChooser.CANCEL_OPTION)
                return; // if user click on Save button
            file = chooser.getSelectedFile();
            try {
                BufferedWriter bw = new BufferedWriter(new FileWriter(file));
                bw.write(textPane.getText());
                bw.close();
     
            } catch (Exception e) {
                JOptionPane.showMessageDialog(this, e.getMessage(), "File Error",
                        JOptionPane.ERROR_MESSAGE);
            }
        }
     
        private JMenuItem makeMenuItem(String name) {
            JMenuItem m = new JMenuItem(name);
            m.addActionListener(this);
            return m;
        }
     
        public static void regularexpressions() throws Exception {
     
            System.out.println("regularexpressions method called");
     
            FileInputStream fstream = new FileInputStream(file);
            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            Pattern p;
            Matcher m;
            String afterReplace = "";
            String strLine;
            String inputText = "";
            while ((strLine = br.readLine()) != null)
                if (strLine.contains("< d v d T i t l e >")) {
                    System.out.println(strLine);
                    inputText = strLine;
                    p = Pattern.compile("\\s+");
                    m = p.matcher(inputText);
                    System.out.println(afterReplace);
                    afterReplace = afterReplace + m.replaceAll("") + "\r\n";
                } else if (strLine.contains("< d v _ i d >")) {
                    System.out.println(strLine);
                    inputText = strLine;
                    p = Pattern.compile("\\s+");
                    m = p.matcher(inputText);
                    System.out.println(afterReplace);
                    afterReplace = afterReplace + m.replaceAll("") + "\r\n";
                } else if (strLine
                        .contains("< / M e t a d a t a P r o v i d e r T i m e >")) {
                    System.out.println(strLine);
                    inputText = strLine;
                    p = Pattern.compile("\\s+");
                    m = p.matcher(inputText);
                    System.out.println(afterReplace);
                    afterReplace = afterReplace + m.replaceAll("") + "\r\n";
                } else if (strLine.contains("< a l b u m A r t i s t >")) {
                    System.out.println(strLine);
                    inputText = strLine;
                    p = Pattern.compile("\\s+");
                    m = p.matcher(inputText);
                    System.out.println(afterReplace);
                    afterReplace = afterReplace + m.replaceAll("") + "\r\n";
                } else if (strLine.contains("< a l b u m T i t l e >")) {
                    System.out.println(strLine);
                    inputText = strLine;
                    p = Pattern.compile("\\s+");
                    m = p.matcher(inputText);
                    System.out.println(afterReplace);
                    afterReplace = afterReplace + m.replaceAll("") + "\r\n";
                }
            FileWriter fstream1 = new FileWriter(file);
            BufferedWriter out = new BufferedWriter(fstream1);
            out.write(afterReplace);
            in.close();
            out.close();
        }
    }
    Hey javaPF thats awesome.

    To be honest i was trying to replace the main method with a consrtuctor but was coming up with all sorts of errors! Think i prefer it the way you have within one class.

    The code compiles fine, however i seem to be getting a null pointer exception when i run the command clean, e.g.
    regularexpressions method called
    Ouch, 'Clean' fell over! java.lang.NullPointerException

    Not sure why though

    Any ideas?

    Thanks

    John

  8. #7
    Senile Half-Wit Freaky Chris's Avatar
    Join Date
    Mar 2009
    Posts
    834
    My Mood
    Cynical
    Thanks
    7
    Thanked 105 Times in 90 Posts

    Default Re: linking two different classes

    My best guess is because file is not being loaded properly. Haven't run it but thats most likely the cause.

    EDIT: Upon running the code it works fine if you load a file. If you don't load a file then it throws the nullpointer expection

    Chris
    Last edited by Freaky Chris; April 27th, 2009 at 01:57 PM.

  9. #8
    Junior Member
    Join Date
    Mar 2009
    Posts
    28
    Thanks
    5
    Thanked 0 Times in 0 Posts

    Default Re: linking two different classes

    Quote Originally Posted by Freaky Chris View Post
    My best guess is because file is not being loaded properly. Haven't run it but thats most likely the cause.
    Yeah for my save and open commands i used JFileChooser.

    I was thinking i might have to do something similar in order to call the file using the clean command.

    I'll have a fiddle with it

    Thanks

    John

  10. #9
    Senile Half-Wit Freaky Chris's Avatar
    Join Date
    Mar 2009
    Posts
    834
    My Mood
    Cynical
    Thanks
    7
    Thanked 105 Times in 90 Posts

    Default Re: linking two different classes

    Read my edit. I clicked open chose a file and the clicked clean and there were no problems.

    Regards,
    Chris

  11. #10
    Junior Member
    Join Date
    Mar 2009
    Posts
    28
    Thanks
    5
    Thanked 0 Times in 0 Posts

    Default Re: linking two different classes

    Ahh right got you now apologies, it works now.

    For some reason i had it working differently in my head lol

    Thanks mate

    John

  12. #11
    Senile Half-Wit Freaky Chris's Avatar
    Join Date
    Mar 2009
    Posts
    834
    My Mood
    Cynical
    Thanks
    7
    Thanked 105 Times in 90 Posts

    Default Re: linking two different classes

    lol, no problem.


    Thanks,
    Chris

  13. #12
    mmm.. coffee JavaPF's Avatar
    Join Date
    May 2008
    Location
    United Kingdom
    Posts
    3,336
    My Mood
    Mellow
    Thanks
    258
    Thanked 294 Times in 227 Posts
    Blog Entries
    4

    Default Re: linking two different classes

    Glad thats all working John
    Please use [highlight=Java] code [/highlight] tags when posting your code.
    Forum Tip: Add to peoples reputation by clicking the button on their useful posts.

Similar Threads

  1. Database connection using NetBeans
    By jcc285 in forum Java IDEs
    Replies: 6
    Last Post: June 9th, 2009, 03:23 AM
  2. Why output is displaying 0 for calculation in java?
    By tazjaime in forum What's Wrong With My Code?
    Replies: 3
    Last Post: April 26th, 2009, 01:18 PM
  3. [SOLVED] Java program using two classes
    By AZBOY2000 in forum Object Oriented Programming
    Replies: 7
    Last Post: April 21st, 2009, 06:55 AM
  4. Problem in merging two java classes
    By madkris in forum Object Oriented Programming
    Replies: 11
    Last Post: March 16th, 2009, 09:02 AM
  5. Java program with abstract class along with two subclasses
    By crazydeo in forum Collections and Generics
    Replies: 2
    Last Post: June 10th, 2008, 11:45 AM