7 Replies - 2666 Views - Last Post: 23 March 2011 - 10:09 AM Rate Topic: -----

#1 jasperFernandes  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 46
  • Joined: 02-March 11

How do i combine three classes into one GUI ?

Posted 20 March 2011 - 09:34 AM

hi, this is 3 classes with their own specific inputs. I wanted to create a GUI that will call and display the outputs of each classes. Can anyone offer me some advice on doing this ?

The first class that is used to extract links form a website. The links extracted will be transferred into text file.

import org.jsoup.Jsoup;
import org.jsoup.helper.Validate;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;


public class SimpleWebCrawler {
	public static void main(String[] args) throws IOException {

		try {
			URL my_url = new URL("http://theworldaccordingtothisgirl.blogspot.com/");
			BufferedReader br = new BufferedReader(new InputStreamReader(
					my_url.openStream()));
			String strTemp = "";
			while (null != (strTemp = br.readLine())) {
				System.out.println(strTemp);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		System.out.println("\n");
		System.out.println("\n");
		System.out.println("\n");

		Validate.isTrue(args.length == 0, "usage: supply url to crawl");
		String url = "http://theworldaccordingtothisgirl.blogspot.com/";
		print("Fetching %s...", url);

		Document doc = Jsoup.connect(url).get();
		Elements links = doc.select("a[href]");

		System.out.println("\n");

		BufferedWriter bw = new BufferedWriter(new FileWriter("abc.txt"));

		for (Element link : links) {
			print("  %s  ", link.attr("abs:href"), trim(link.text(), 35));

			bw.write(link.attr("abs:href"));
			bw.write(System.getProperty("line.separator"));
		}
		bw.flush();
		bw.close();

	}

	private static void print(String msg, Object... args) {
		System.out.println(String.format(msg, args));
	}

	private static String trim(String s, int width) {
		if (s.length() > width)
			return s.substring(0, width - 1) + ".";
		else
			return s;

	}

}



the second class uses the link gathered above and extract their contents and transfer into a text file.

import net.htmlparser.jericho.*;
import java.util.*;
import java.io.*;
import java.net.*;

public class RenderToText {

	public static void main(String[] args) throws IOException {
		
		
			
			//Starting to write files

			FileReader fr = new FileReader(
					"C:\\Users\\user\\fypworkspace\\TextCrawler\\abc.txt");
			BufferedReader textReader = new BufferedReader(fr);

			// for each URL, process the URL and render the HTML file
			int numberofURL = 10;
			String[] URL = new String[numberofURL];
			int a;
			
			
			

			// For each URL, assign one text file to store the contents

			// for each URL, extract the URL contents

			for (a = 0; a < numberofURL; a++) {
				for (int i = 0; i < numberofURL; i++) {

					URL[a] = textReader.readLine();
                    try{
					try {
						try {
							// Render the text from the HTML file
							String sourceUrlString = URL[a];

							if (args.length == 0)
								System.err.println("Using argument of \""
										+ sourceUrlString + '"');
							else
								sourceUrlString = args[0];
							if (sourceUrlString.indexOf(':') == -1)
								sourceUrlString = "file:" + sourceUrlString;
							Source source = new Source(new URL(sourceUrlString));
							String renderedText = source.getRenderer()
									.toString();
							System.out
									.println("\nSimple rendering of the HTML document:\n");
							System.out.println(renderedText);

							// Write the rendered text to a text file

							String filename = ("abc" + i + ".txt");
							Writer output = null;
							String text = renderedText;
							File file = new File(filename);
							output = new BufferedWriter(new FileWriter(file));
							output.write(text);
							output.close();
							System.out.println("Your file has been written");

							// Count the number of words available in the
							// rendered text.

							BufferedReader br = new BufferedReader(
									new FileReader(
											"C:\\Users\\user\\fypworkspace\\TextRenderer\\abc"
													+ i + ".txt"));
							String line = "", str = "";
							int count = 0;
							while ((line = br.readLine()) != null) {
								str += line + " ";

							}
							StringTokenizer st = new StringTokenizer(str);
							while (st.hasMoreTokens()) {
								@SuppressWarnings("unused")
								String s = st.nextToken();
								count++;
							}
							System.out.println("File has " + count + " words.");
						} catch (UnknownServiceException ex) {
							System.out
									.println("The following url cannot be processed");

						}

						System.out.println("\n");
						System.out.println("\n");
						System.out.println("\n");
					} catch (NullPointerException ex) {
						System.out.println("End of URL");
						System.exit(0);
					}
				}catch(IOException ex){
					System.out.println("The following url cannot be processed due to the need to login");
				}
			}
		}
	}
}




The third class does some text processing stuff and display some datas.

import net.htmlparser.jericho.*;
import java.util.*;
import java.io.*;
import java.net.*;

public class RenderToText {

	public static void main(String[] args) throws IOException {
		
		
			
			//Starting to write files

			FileReader fr = new FileReader(
					"C:\\Users\\user\\fypworkspace\\TextCrawler\\abc.txt");
			BufferedReader textReader = new BufferedReader(fr);

			// for each URL, process the URL and render the HTML file
			int numberofURL = 10;
			String[] URL = new String[numberofURL];
			int a;
			
			
			

			// For each URL, assign one text file to store the contents

			// for each URL, extract the URL contents

			for (a = 0; a < numberofURL; a++) {
				for (int i = 0; i < numberofURL; i++) {

					URL[a] = textReader.readLine();
                    try{
					try {
						try {
							// Render the text from the HTML file
							String sourceUrlString = URL[a];

							if (args.length == 0)
								System.err.println("Using argument of \""
										+ sourceUrlString + '"');
							else
								sourceUrlString = args[0];
							if (sourceUrlString.indexOf(':') == -1)
								sourceUrlString = "file:" + sourceUrlString;
							Source source = new Source(new URL(sourceUrlString));
							String renderedText = source.getRenderer()
									.toString();
							System.out
									.println("\nSimple rendering of the HTML document:\n");
							System.out.println(renderedText);

							// Write the rendered text to a text file

							String filename = ("abc" + i + ".txt");
							Writer output = null;
							String text = renderedText;
							File file = new File(filename);
							output = new BufferedWriter(new FileWriter(file));
							output.write(text);
							output.close();
							System.out.println("Your file has been written");

							// Count the number of words available in the
							// rendered text.

							BufferedReader br = new BufferedReader(
									new FileReader(
											"C:\\Users\\user\\fypworkspace\\TextRenderer\\abc"
													+ i + ".txt"));
							String line = "", str = "";
							int count = 0;
							while ((line = br.readLine()) != null) {
								str += line + " ";

							}
							StringTokenizer st = new StringTokenizer(str);
							while (st.hasMoreTokens()) {
								@SuppressWarnings("unused")
								String s = st.nextToken();
								count++;
							}
							System.out.println("File has " + count + " words.");
						} catch (UnknownServiceException ex) {
							System.out
									.println("The following url cannot be processed");

						}

						System.out.println("\n");
						System.out.println("\n");
						System.out.println("\n");
					} catch (NullPointerException ex) {
						System.out.println("End of URL");
						System.exit(0);
					}
				}catch(IOException ex){
					System.out.println("The following url cannot be processed due to the need to login");
				}
			}
		}
	}
}




I just wanted to combine this three classes into one GUI with 3 buttons to call this classes and display their output as the outputs in console. I have no experience in GUI so a through advice would be appreciated. Thanks.

Is This A Good Question/Topic? 0
  • +

Replies To: How do i combine three classes into one GUI ?

#2 GregBrannon  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2194
  • View blog
  • Posts: 5,222
  • Joined: 10-September 10

Re: How do i combine three classes into one GUI ?

Posted 20 March 2011 - 10:16 AM

Pretty simple, a good starting exercise for learning how to build a GUI in Java. I suggest you use Swing, start with JFrame, add 3 buttons to it, add listeners to the buttons, and when the listeners fire, call the 3 classes to do what they do. Currently, each of your classes has a main() method. Your new architecture may involve a separate class with a main method that builds the GUI (possibly another class) and does the necessary GUI housekeeping/management. With that architecture, you'd remove the main() methods in your existing classes.

Review the Swing tutorials here on DIC. Look for JFrames, adding buttons, using ActionListeners. You can find the same searching the internet or in the Java site tutorials.

It's a good starting project from which you should learn a lot. Come back if you need help.
Was This Post Helpful? 0
  • +
  • -

#3 jasperFernandes  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 46
  • Joined: 02-March 11

Re: How do i combine three classes into one GUI ?

Posted 22 March 2011 - 08:40 AM

View PostGregBrannon, on 20 March 2011 - 10:16 AM, said:

Pretty simple, a good starting exercise for learning how to build a GUI in Java. I suggest you use Swing, start with JFrame, add 3 buttons to it, add listeners to the buttons, and when the listeners fire, call the 3 classes to do what they do. Currently, each of your classes has a main() method. Your new architecture may involve a separate class with a main method that builds the GUI (possibly another class) and does the necessary GUI housekeeping/management. With that architecture, you'd remove the main() methods in your existing classes.

Review the Swing tutorials here on DIC. Look for JFrames, adding buttons, using ActionListeners. You can find the same searching the internet or in the Java site tutorials.

It's a good starting project from which you should learn a lot. Come back if you need help.


Hi, This is my first class where when i click a button, i need this class to display the output of this class.
This class program as follows :

import org.jsoup.Jsoup;
import org.jsoup.helper.Validate;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;


public class SimpleWebCrawler {
	public static void main(String[] args) throws IOException {

		try {
			URL my_url = new URL("http://theworldaccordingtothisgirl.blogspot.com/");
			BufferedReader br = new BufferedReader(new InputStreamReader(
					my_url.openStream()));
			String strTemp = "";
			while (null != (strTemp = br.readLine())) {
				System.out.println(strTemp);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		System.out.println("\n");
		System.out.println("\n");
		System.out.println("\n");

		Validate.isTrue(args.length == 0, "usage: supply url to crawl");
		String url = "http://theworldaccordingtothisgirl.blogspot.com/";
		print("Fetching %s...", url);

		Document doc = Jsoup.connect(url).get();
		Elements links = doc.select("a[href]");

		System.out.println("\n");

		BufferedWriter bw = new BufferedWriter(new FileWriter("abc.txt"));

		for (Element link : links) {
			print("  %s  ", link.attr("abs:href"), trim(link.text(), 35));

			bw.write(link.attr("abs:href"));
			bw.write(System.getProperty("line.separator"));
		}
		bw.flush();
		bw.close();

	}

	private static void print(String msg, Object... args) {
		System.out.println(String.format(msg, args));
	}

	private static String trim(String s, int width) {
		if (s.length() > width)
			return s.substring(0, width - 1) + ".";
		else
			return s;

	}

}



My simple GUI program consisting a three buttons where as follows :

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * NewJFrame.java
 *
 * Created on Mar 22, 2011, 11:16:34 PM
 */



/**
 *
 * @author user
 */
public class Main extends javax.swing.JFrame {

    /** Creates new form NewJFrame */
    public Main() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("Crawl");

        jButton2.setText("Calculate Similarity");

        jButton3.setText("Extract Text");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(90, 90, 90)
                        .addComponent(jButton1)
                        .addGap(51, 51, 51)
                        .addComponent(jButton3))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(121, 121, 121)
                        .addComponent(jButton2)))
                .addContainerGap(107, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(82, 82, 82)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton3)
                    .addComponent(jButton1))
                .addGap(18, 18, 18)
                .addComponent(jButton2)
                .addContainerGap(154, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>
    
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
    SimpleWebCrawler swc = new SimpleWebCrawler();
    }

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Main().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    // End of variables declaration

}



When i click on the button jButton1, there is nothing happen. How do i make it to display their output ?
Was This Post Helpful? 0
  • +
  • -

#4 TFoSSDQ  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 123
  • View blog
  • Posts: 253
  • Joined: 09-December 10

Re: How do i combine three classes into one GUI ?

Posted 22 March 2011 - 08:49 AM

First off, please don't use the GUI builder as the code is ugly and hard to read. swing is pretty simple and should be written by hand.

About your button not doing anything, you would need to add an ActionListener to the button for it to do anything and you're going to have to define public void actionPerformed(ActionEvent e) wherever you create the ActionListener

An example:
jButton1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e)
        {
            //some code to be performed
        }
    });



A class can also implement ActionListener and you can make that class the argument for addActionListener():
public class SomeListener implements ActionListener
{
    public void actionPerformed(ActionEvent e)
    {
        //do some code
    }
}
//and
//.
//.
//.
SomeListener listener = new SomeListener();
jButton1.addActionListener(listener);


This post has been edited by TFoSSDQ: 22 March 2011 - 08:54 AM

Was This Post Helpful? 0
  • +
  • -

#5 jasperFernandes  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 46
  • Joined: 02-March 11

Re: How do i combine three classes into one GUI ?

Posted 23 March 2011 - 09:06 AM

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileNotFoundException;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JFrame;
 
public class Main {
 
    private static void createAndShowGUI()  {
 
        JFrame frame1 = new JFrame("JAVA");
        frame1.setSize(300,400);
        frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
        JButton button = new JButton(" TextProcessing Button");
        JButton button1 = new JButton("Extract Links");
        
        //Add action listener to button
        
        button.addActionListener(new ActionListener() {
 
            public void actionPerformed(ActionEvent e)
            {
                try {
					readFile.main(null);
				} catch (FileNotFoundException e1) {					
					e1.printStackTrace();
				}
            }
        });      
      //Add action listener to button 1
        button1.addActionListener(new ActionListener() {
        	public void actionPerformed(ActionEvent e)
            {
        		try {
					RenderToText.main(null);
				} catch (IOException e1) {
					
					e1.printStackTrace();
				}
            }
        });
 
        frame1.getContentPane().add(button);
        frame1.getContentPane().add(button1);
        
       
        frame1.setVisible(true);
    }
 
 
    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}


this is my code to create 2 buttons with their own TODO code. However, the GUI only displays one button. Where do i miss ? I would appreciate a good pointing. Thank you.
Was This Post Helpful? 0
  • +
  • -

#6 TFoSSDQ  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 123
  • View blog
  • Posts: 253
  • Joined: 09-December 10

Re: How do i combine three classes into one GUI ?

Posted 23 March 2011 - 09:39 AM

JFrame has a BorderLayout and how you've set it up will only hold one at a time as it tries to add both to center. Change the layout or use a JPanel.

This post has been edited by TFoSSDQ: 23 March 2011 - 09:41 AM

Was This Post Helpful? 0
  • +
  • -

#7 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10190
  • View blog
  • Posts: 37,635
  • Joined: 27-December 08

Re: How do i combine three classes into one GUI ?

Posted 23 March 2011 - 09:39 AM

The LayoutManager for a JFrame by default is a BorderLayout, and the add() method is adding the JButtons to the center. Only one JComponent can occupy a region in a BorderLayout. You need to get the Content Pane and set the LayoutManager to something else, like FlowLayout.
Was This Post Helpful? 0
  • +
  • -

#8 jasperFernandes  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 46
  • Joined: 02-March 11

Re: How do i combine three classes into one GUI ?

Posted 23 March 2011 - 10:09 AM

hi, thanks for your pointers. I create a flow layout. However, i encounter another problem where when i click the gui, it processes the TODO code. However, the GUI completely freezes and i cant close the interface from the GUI. I can only stop the GUI from the stop command in the console.

import java.awt.ComponentOrientation;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileNotFoundException;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JFrame;
 
public class Main {
 
    private static void createAndShowGUI()  {
 
        JFrame frame1 = new JFrame("JAVA");
        frame1.setSize(300,400);
        frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        FlowLayout experimentLayout = new FlowLayout();
        experimentLayout.setAlignment(FlowLayout.TRAILING);
        frame1.setLayout(experimentLayout);
 
       
        
        JButton button = new JButton("Similarity Calculation");
        JButton button1 = new JButton("Render To Text");
        
      
        
        //Add action listener to button
        
        button.addActionListener(new ActionListener() {
 
            public void actionPerformed(ActionEvent e)
            {
                try {
					readFile.main(null);
				} catch (FileNotFoundException e1) {					
					e1.printStackTrace();
				}
            }
        });      
      //Add action listener to button 1
        button1.addActionListener(new ActionListener() {
        	public void actionPerformed(ActionEvent e)
            {
        		try {
					RenderToText.main(null);
				} catch (IOException e1) {
					
					e1.printStackTrace();
				}
            }
        });
 
        frame1.getContentPane().add(button);
        frame1.getContentPane().add(button1);
        
       
        frame1.setVisible(true);
    }
 
 
    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1