KirkPatrick 28 Junior Poster

What have you come up with thus far? Show us your code and perhaps we can help you. Or are you looking for a starting point?

KirkPatrick 28 Junior Poster

This is sort of a follow up on my previous thread. I am looking into ways to click buttons, hyperlinks, or enter info into websites from a java program.

So I have taken a look into the following site:

http://www.informit.com/guides/content.aspx?g=java&seqNum=44

The page explains how to use the yahoo search. Here is the code:

import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;

public class PostExample {
 public static void main( String[] args ) {
   String url = "http://search.yahoo.com/search";
   try {
    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod( url );

	 // Configure the form parameters
	 method.addParameter( "p", "Java" );

	 // Execute the POST method
    int statusCode = client.executeMethod( method );
    if( statusCode != -1 ) {
      String contents = method.getResponseBodyAsString();
      method.releaseConnection();
      System.out.println( contents );
    }
   }
   catch( Exception e ) {
    e.printStackTrace();
   }
 }
}

A lot of the code isn't too hard to understand, but what I am wondering is how does it know to click the search button and not some other hyperlink on the page? I understand there is only one button on the page, but what if there are multiple ones? What if I want to click a specific hyperlink? What if the hyperlink that I'm wanting executes javascript?

Anyways I'm just looking for someone that might have some knowledge on the area and is willing to explain it a bit.

KirkPatrick 28 Junior Poster

I apologize that I haven't had the chance to reply back with progress. I have managed to get it to do what I was intending.

My next step is being able to click buttons and links through my java program. I believe I need to read up on http post.

Thanks for all your help, its much appreciated

KirkPatrick 28 Junior Poster

I was testing it out and am wondering why it only prints out 1 letter at a time?

Here is my example code:

String link = "http://www.daniweb.com/forums/forum9.html";
        ArrayList pageInfo = new ArrayList();
        
        try {
            URL url = new URL(link);
            BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
            
            String line;

            while((line = br.readLine()) != null) {
                line = line.trim();
                String pat = "<div class=\"([a-zA-Z0-9])+\""; //pattern check between a-z and 0-9 -
                Pattern pattern = Pattern.compile(pat);
                Matcher matcher = pattern.matcher(line);
                
                boolean matchFound = matcher.find();
                if (matchFound) {
                    String name = matcher.group(1);
                    pageInfo.add(name);
                    System.out.println(name);
                    
                }
            }
            
            System.out.println(pageInfo);
            
        } catch (MalformedURLException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException e) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, e);
        }
        
    }

and here is what the output is:

p
d
g
x
c
c
c
c
v
i
e
e
v
x
c
c
c
c
2
x
c
c
c
c
t
d
m
t
[p, d, g, x, c, c, c, c, v, i, e, e, v, x, c, c, c, c, 2, x, c, c, c, c, t, d, m, t]

I assume I would have to change my pattern?

KirkPatrick 28 Junior Poster

Sorry, I must have missed this in my previous posts, but what did your baseUrl and par look like?

I would assume it is something like this:

baseUrl = "http://www.daniweb.com/forums/forum9"
par = "-desc-"(0-9)".html"

Or am I thinking of it wrong?

KirkPatrick 28 Junior Poster

the page had a lot of pictures, I only wanted the ones with that attribute

Alright, thanks bud. I will continue working on this side project of mine and I'll be sure to report back on the progress.

I will need to look into expressions a bit more as i don't fully understand them all, some seem pretty complicated.

Also, are you aware of how to interact with websites? Such as the buttons, drop menus, etc?

KirkPatrick 28 Junior Poster

So essentially my if(matchFound) would be much simpler, like so?

ArrayList info = new Arraylist();

                        if (matchFound) {
                            String name=matcher.group(1);
                            info.add(name); //just add the info from the string inside title
                                                       
                        }
                      //print out info in arraylist
                      //write info from arraylist to file

Thank you for going into detail about the groups, that is quite helpful. Just curious, but why do you include: alt=\"Picture\"/></div> ?

KirkPatrick 28 Junior Poster

if (isWindows == true) is a dumb way of saying if (isWindows)

haha agreed, unless for some reason it's set to false above ;)

thanks for the insight as well, i wasn't aware that was the reason for creating TRUE and FALSE

KirkPatrick 28 Junior Poster

Public final static Boolean FALSE=new Boolean(false);
Public final static Boolean TRUE=new Boolean(true);
what is the meaning of above two statements?

There should be more code to go with this, otherwise it's pretty hard to tell what you are trying to accomplish.

I'm also not quite sure why someone would want to create a true/false when the point of a boolean is to determine whether it is true or false.

For example:

private boolean isWindows;

if (isWindows == true) 
    // do something only a windows os can do
else
    // do something only a unix os can do

Obviously there are more operating system's than those two but that shows how a boolean would work. Or at least how I use my booleans instead of creating true false

KirkPatrick 28 Junior Poster

Wow you guys have been very helpful! I'm appreciative for each of your posts

(Yes, the HTML page source is just marked up text)

Sorry I had left the other day before getting back to you about it, I had assumed it read straight from the source, but just wanted to make sure. Thanks for confirming that.
----

this is some code I wrote to make a custom crawler to get images from a site. just change the pattern and the method that stores the string (Bajador is a class that downloads the image in my case) and put everything in a loop that goes through all the urls you wish to examine.

try {
                    URL url = new URL(baseURL+"/index.php?id="+par);
                  BufferedReader br= new BufferedReader( new InputStreamReader(url.openStream()));
                  String line;
                  while((line=br.readLine())!=null){
                      line=line.trim();
                      String pat="<img src=\"/(\\w*).jpg\" alt=\"Picture\"/></div>";
                       Pattern pattern = Pattern.compile(pat);
                       Matcher matcher = pattern.matcher(line);
                       boolean matchFound = matcher.find();
                        if (matchFound) {
                            String nombre=matcher.group(1);
                            String urlI=baseURL+"/file/"+nombre+".jpg";
                            Bajador baj= new Bajador(baseURL,nombre,par);
                            baj.start();
                          //  baja(baseURL,nombre);
                           
                        }
                  }
                } catch (MalformedURLException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IOException e) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, e);
                }

Hope this help you.

That helped me quite a bit, I read into patterns and while it seems a bit confusing I understood enough to where I believe you are correct in saying I only needed to search from a-z and 0-9.

I am left a bit confused about some of your code, so if you don't mind I'll just ask the questions here for a better understanding.


       
KirkPatrick 28 Junior Poster

I don't get your question. are you asking how to get all the titles programaticly or how to store the title strings?

if you are asking how to ge tthe titles, I would suggest to read line by line and use a regular expression to get the string you like.

Take a look at the java Pattern class: http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/Pattern.html

You probably will be doing something like title=\"([a-zA-Z0-9])+\" and then get the string from the capturing group. (I haven't done this in a while so the example is probably wrong, but it is the idea.)

I did something like this but I have it at home. I'll rescue it at night to show you.

I'll see if I can clear up my question a bit better for your understanding.

What I am wanting to do is create a program that will read a webpages source, grab a specific field, and write what the fields string down in a text file.

So another example would be, you're viewing this forum and lets say there is a field in the source named thread title.

Now in the source you see: thread_title="title1"

A few lines down in the same source you see thread_title again but this time it is: thread_title="title2"

Now lets say there are a hundred of these per page, and I am wanting to get all of them and write them to a text file, once page one is done I want to go to …

KirkPatrick 28 Junior Poster

Much appreciated response ezzaral, just one quick question when reading the text from the url, does that automatically read the source of the page?

KirkPatrick 28 Junior Poster

I haven't ever messed with any webpages through java and I'm kind of curious as to how it would work. I have a specific question that perhaps someone will be able to answer.

How would one go about pulling certain information from a forum? To better understand what I am asking, I'll give an example:

Lets say I am surfing this forum and am currently at:

http://www.daniweb.com/forums/forum9.html

Then I click view source, this gives me the source of the current page opened.

Now lets say I want to pull out every title in there. Ex. title=""

After pulling out each title I would want to add it to a text file or something of the sort so I can refer to it later. For the mean time I would probably add it to an arraylist of some sort because the next thing I would want it to do is click next page and do it to the following page.

Can anyone shed some light on how to do such a thing? Or perhaps let me know what I need to read up on to get where I'm wanting to go.

KirkPatrick 28 Junior Poster

Next time put your code in tags, it makes it easier to read.

As for the text to open a web page, I would just have it a jLabel of a jButton. I haven't ever done it, but it is possible. An example is located here:

http://stackoverflow.com/questions/527719/how-to-add-hyperlink-in-jlabel

If you need more examples, you could always search google with a phrase like so: java jlabel hyperlink

KirkPatrick 28 Junior Poster

"Selection" is nothing more than a boolean. You can represent that however you choose.

The box layout just stacks the components vertically. You could use grid or grid bag as well. The point is that each entry is a JPanel component.

So the way I have it right now (through gridBagLayout) it automatically stacks them to the top would technically be sufficient if I add a boolean for isSelected?

I also have to remove whatever information is in the viewObject from a arraylist or vector depending on whether it is selected in this jPanel.

KirkPatrick 28 Junior Poster

but also to help me understand exactly how this works as i havent been able to find any good insructional information on this particular topic.

public int calcDistance(int distance, int endMiles, int startMiles)
    {
        distance = endMiles - startMiles;
        return distance;
    }

the above will calculate the distance obviously. It has three parameters: distance, end miles, and start miles. Inside you have it calculate the distance automatically.

public double calcMPG(int mpg, int distance, int gallons)
    {
        mpg = distance/ gallons;
        return mpg;
        
    }

this could be explained almost exactly like the one above, but with different paramters

//main method
    public static void main(String[] args)
    {
        int startMiles1 = 55;
        int endMiles1 = 250;
        int gallons1 = 15;
        
        int distance1, mpg1;

        distance1 = calcDistance(distance1,endMiles1,startMiles1);
        mpg1 = calcMPG(mpg1 ,distance1);
        
        System.out.println("                     Gas Mileage Calculations");
        System.out.println("Type of Car   Start Miles   End Miles   Distance   Gallons   Miles/Gallons");
        System.out.println("==========================================================================");
        System.out.printf("Saturn %4.2f    %4.2f    %4.2f    %4.2f    %4.2f    %4.2f" + startMiles1 + endMiles1 + distance1 +  gallons1 + mpg1);
    }
}

This main method sets the start miles, end miles, and gallons with specific integers. Distance and mpg have no specific integers but will receive them once they are plugged in.

distance1 = calcDistance(distance1, endMiles1, startMile1);

This is basically saying this: calcDistance(distance1, 250, 55);
Now remember calcDistance figures out the distance1 for you due to the calculation inside the method. So distance1 will now equal 195.

mpg1 = calcMPG(mpg1, distance1);

This will be: calcMPG(mpg1, 195);
So plug that into the equation: mpg = …

KirkPatrick 28 Junior Poster

I can't figure why you would want to render it in a list. If you want to display a series of panel entries they you would be better off putting them in a vertical box layout in a scroll pane.

What I had originally done was put them in a jPanel inside a scroll pane. However, I realized I also had to be able to select the object in case I wanted to delete from the panel and arraylist or vector that the entry would be stored in.

I'm not familiar with a vertical box layout, I would assume I wouldn't be able to select the object though in case I need to remove the entry

KirkPatrick 28 Junior Poster

You could create an integer and inside your if else statements add 'x' amount of points per correct answer.

if (question is correct) {
//add points to the int
}

You could also display the points somewhere in the game so they know how they are doing if you'd like.

So it should be quite simple, just create an integer that will keep track of the points, for every correct question add points (in your if else statements), when the timer ends pull the final value of the integer. Once the game restarts, reset the integer

KirkPatrick 28 Junior Poster

Are you wanting to stick with a certain layout? Or are you willing to try out other layouts? If you are, you could use a gridBagLayout and set the x and y weight to how you are wanting it to adjust.

I believe that will do what you are looking for, if I read you correctly

KirkPatrick 28 Junior Poster

Thanks for the advice BestJewSinceJC, sorry for such a late response. I have just now gotten back to the project that I'm working on with this jList renderer.

I haven't messed with making a custom render before so I'm a bit clueless on how to get it working the way I want it to. The basic structure seems to be like so:

class MyCellRenderer extends DatabaseObject implements ListCellRenderer {
        final static ViewObject vo = new ViewObject();     
        
        public Component getListCellRendererComponent (JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            
            //set ViewObject
            
                if (isSelected) {
                    setBackground(list.getSelectionBackground());
                    setForeground(list.getSelectionForeground());
                } else {
                    setBackground(list.getBackgroud());
                    setForeground(list.getForeground());
                }      
                setEnabled(list.isEnabled());
                setFont(list.getFont());
                setOpaque(true);
                return this;
            }
        }
    }
    //set cell renderer

I'm not quite sure how I should be setting the viewobject exactly though. What's going to happen is when I click a button I'm wanting information to go into the viewobject which would then go onto this custom renderer.

If anyone is able to give me a hint on how to continue setting this up, I'd be grateful.

In the example I was viewing, it had the following code:

String s = value.toString();
         setText(s);
         setIcon((s.length() > 10) ? longIcon : shortIcon);

However, I'm not aware of there being a setObject which is where I remain confused a bit.

KirkPatrick 28 Junior Poster

Hey guys I'm a bit confused here as I haven't edited a renderer before.

My situation is that I have a custom object that I have created. It has a few jLabels, textboxes, and a combo box. And what I'm wanting to do it make it display on a jList. For now we can call the object ViewObject.

Can someone explain or show me how I would go about doing this?

I have checked the Java Docs, but they don't quite seem to make a whole lot of sense to me.

KirkPatrick 28 Junior Poster

Main class defines getter for these Strings:
public String getDefaultFileLocation() { return defaultLocn; }

Main class instatiates an instance of a subclass, passing itself as a parameter:
SubClass sub = new SubClass(this);

SubClass keeps a copy in the constructor:
public SubClass(MainClass main) {
this.main = main);
}

SubClass methods can then query the Strngs from main:
File f = new File(main.getDefaultFileLocation());

Thank you, I think I understand what I need to do. I'll give it a go when I get the chance and get back to you.


*Edit*
Yeah I have looked into System.getProperty, I just haven't applied it into my program quite yet. The following is one I had looked into awhile back when I was deciding how I would determine which OS the computer was using

String osName = System.getProperty("os.name");

I don't know a whole lot about property files at the moment either so I'm reading into that as well.

KirkPatrick 28 Junior Poster

You can pass a reference to the main class into the constructors of the other classes, so that they can then call getter methods in the main class. Sharing the Strings themselves may be a bad idea - what happens when one of these values changes? Much better to use getters and never keep any local copies.

The strings are file locations, one being for a linux based system and the other for a windows based system so they shouldn't change. However, I agree it would be of much more use if I didn't limit them like that.

I've used getters before, but I'm not quite sure I follow you on how you would pull them from the main class. Could you elaborate? Or show a small example?

KirkPatrick 28 Junior Poster

I currently have strings that are all the same throughout my classes, I was just wondering how I could make the value of the strings pass from the main class to the rest of the classes.

My reasons being that I am wanting to create a property file and have it set the strings to a default value which will access the main class.

Could someone briefly explain how I would go about this?

KirkPatrick 28 Junior Poster

Just copy everything from lines 3-10 into your method and change the variables to use your method parameters.

Thats what I had tried originally, but it gives me a problem where the viewobject is

panel.add(object, gridBagConstraints);

It wants me to cast object to component, would there be a problem doing this? Or should I just change my parameter to a Component object instead of Object object

KirkPatrick 28 Junior Poster

Well I'm going through a lot of my code and wanting to clean it up a bit by creating functions to do the necessary tasks instead of having code that is multiple lines long.

For example, I use the following code multiple times

ViewObject vo = new ViewObject(a, b, c, d, e, f);

        GridBagConstraints gridBagConstraints = new GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = row;
        gridBagConstraints.anchor = GridBagConstraints.NORTHWEST;
        gridBagConstraints.fill = GridBagConstraints.HORIZONTAL;
        gridBagConstraints.weightx = 1.0;

        jPanel.add(vo, gridBagConstraints);

So if I wanted to create a function to take care of this but be able to change the viewobject, gridy, and panel what would the function look like?

I know the parameters would be something like:

public void constraints(int row, Object object, JPanel panel){

    }

Basically I'm just looking for how to make gridy = row, vo = object, jPanel = panel and my mind seems to be coming up with a blank

KirkPatrick 28 Junior Poster
class DatabaseObject extends javax.swing.JPanel

This rings all kinds of alarm bells!

The normal way of doing things is to have a "database object" that encapsulates the data items and provides accessors, as well as methods for saving/retrieving them (possibly delageted). You then have a GUI object that takes a database object as a parameter and displays it and/or collects new data values for it.

I don't know enough about your app to know whether you should be doing something different, but it comes as no surprise that you are running into problems with saving.
I can go into more detail if you think it's relevant.

Thanks for the reply James.

I couldn't find a way to set the width of each textfield other than setting the max, min, and preferred all to the same thing.

As for saving, I have decided to grab all the information entered in the database gui and instantly add it to an arraylist or vector and clear the panel that i add the display objects to and then have it add the objects from the arraylist or vector of database objects surrounded by a for loop.


Not sure if that makes sense, but I believe it should work. I'll be sure to post back when I get to testing it.

KirkPatrick 28 Junior Poster

Alright I have created an object, its a simple object. Basically just textfields and a combobox. I have them all in a gridbag layout with weightx and weight y set to one so that they fill out the panel I place them on.

Question 1:
What I'm wanting to do is basically re-create a jTable look and feel (where the columns all line up). So I'm wondering if there is a way where I can set the object's textfields to a specific width and add an option to allow the user to expand the field (as you see in the jtable).


Question 2:
I'm wondering how I can save all the information I put in these objects as well as deleting them. Basically every time I click a button it will add information from textfields to the object and display the object in a panel.

From what I have read, I might need to make the objects selectable by writing a custom list renderer and placing them on a list instead of panel.

Anyways here is my code for the object (minus the GUI type code, which i can add if needed):

public class DatabaseObject extends javax.swing.JPanel {

  private String fieldOne;
  private String fieldTwo;
  private String fieldThree;
  private String fieldFour;
  private String fieldFive;
  private String fieldSix;
  private ArrayList comboBoxNumber;

    /** Creates new form DatabaseObject */
    public DatabaseObject(String fieldOne, String fieldTwo, String fieldThree, String fieldFour, String fieldFive, String fieldSix, ArrayList comboBoxNumber ) { …
KirkPatrick 28 Junior Poster

Apologies, yes it is actionperformed.

Yeah making it a global class variable should work, I suppose I just thought there might be a way to do it inside the actionperformed.

Nonetheless, it gets the job done. Thanks for the response Vernon

KirkPatrick 28 Junior Poster

Its been awhile since I have toyed around with java, so I'm a bit rusty. But decided to mess with it today.

I have a jPanel that I will be adding objects to, but I want to add the in a new row each time a button is clicked. Anyways the problem is, every time I click the button it resets my integer which I increment.

Here is the snipper:

int row = 0;
        row++;

         //constraints
        GridBagConstraints gridBagConstraints = new GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = row;
        gridBagConstraints.anchor = GridBagConstraints.NORTHWEST;
        gridBagConstraints.fill = GridBagConstraints.HORIZONTAL;
        gridBagConstraints.weightx = 1.0;

        //add object to panel
        jPanel1.add(object, gridBagConstraints);

Basically since I set int row = 0 it resets it to 0 every time I click the button.

Anyone able to offer a quick solution?

KirkPatrick 28 Junior Poster

I think the thread maker is wanting someone else to finish the project, which clearly won't happen here.

Its not too hard to finish though, just make sure you get the values from the textfields, set up a few if else statements for the jbuttons and then make a class to do the calculations.

Get text entered from textfield:

jTextField1.getText()
//use to get the needed values, also this will give you a string so you'll want to change it to int

Determine which radio button is selected:

if (jRadioButton1.isSelected()) {
            //set interest rate to 5%
        } else if (jRadioButton2.isSelected()) {
            //set interest rate to 10%
        } else if (jRadioButton3.isSelected()) {
            i//set interest rate to 12%
        }

Come up with some code and I'm sure there will be more help offered

KirkPatrick 28 Junior Poster

My question is that instead of reading to the console how would I get this informaton into the JMenus.

Are you wanting to have 3 jMenus reading like so:

jMenu1:
Bike
Car

jMenu2:
Schwinn
Mercedes

jMenu3:
45.00
98,000

If thats how you are wanting them split, then split them using "," and specify each column, perhaps save each to an arraylist, and then have your menus get the value based on column.


*edit*
Here is an example snippet to help you understand

BufferedReader reader = new BufferedReader(new FileReader("C:\\myfile.fileExtension"));

        ArrayList<String> list1 = new ArrayList<String>();

        try {
            //this checks for headers, if you dont have them, ignore this part
            boolean bHeadersDone = false;
            while (reader.ready()) {
                String headerInfo = reader.readLine();

                if (!bHeadersDone) {
                    if (headerInfo.contains("Your last header here")) {
                        bHeadersDone = true;
                    }
                }
                else {
                    //splitting file into 3 columns
                    String[] info = list1Info.split("," , 3);
                    Column1Info = info[0];
                    Column2Info = info[1];
                    Column3Info = info[2];
                    
                    //adding columns to arraylist
                    if(!list1.equals(0)) {

                        list1.add(itemA);
                        list1.add(itemB);
                        list1.add(itemC);

                        //do what you want here
                        //maybe add them to jMenu here
                        //catch exceptions

I hope that helps a little bit

KirkPatrick 28 Junior Poster

A great example shown by the member above (BestJewSinceJC) is located here, if you have any confusion:

http://www.daniweb.com/forums/post869395-2.html
KirkPatrick 28 Junior Poster

Posting the exact exceptions might be helpful to those who are wanting to help you. (i didn't see them posted, but could have missed them. If they aren't in your post, add them and it should help in getting a response)

KirkPatrick 28 Junior Poster

He could even look at snippets that have been posted on this very forum and learn from them.

http://www.daniweb.com/code/snippet1271.html

That link shows a very basic 'translator' to pig latin.

There are some very helpful people on this forum; however, as masijade said, they are not here to do your work for you. I have found that when I post and show that I am trying to learn it and make progress here and there, they are more than willing to help out.

Godstryke had a good list of what you should do if you aren't sure where to start.

Best of luck :)

KirkPatrick 28 Junior Poster

Okay well I have fixed the previous problem, but now its not quite working the way I am wanting it to work.

for(int i = 0; i< tableModel.getRowCount(); i++) {
                    Column1= (String) tableModel.getValueAt(i, 1);
                    Column2 = (String) tableModel.getValueAt(i, 2);
                    Column3 = (String) tableModel.getValueAt(i, 3);
                    Column4 = (String) tableModel.getValueAt(i, 4);

                    for (int h = 0; h < box.getItemCount(); h++) {
                        Column5= (String) box.getItemAt(h);
                    }

                    
                    
                    System.out.println("Print whats in >>" + Column1 + "," + Column2 + "," + Column3 + "," + Column4 + "," + Column5 + "<<");

            }

Info submitted to columns:

Column1: info1
Column2: info2
Column3: info3
Column4: info4
Column5: data1, data2, data3, data4, data5, data6, data7, data8, data9, data10

Problem (it prints out):

Print whats in >> info1, info2, info3, info4, data10 <<

What I'm wanting it to print/write:

Print whats in >> info1, info2, info3, info4, data1, data2, data3, data4, data5, data6, data7, data8, data9, data10 <<

Then I go ahead and enter another set of data into it and the jComboBox seems to only recall the latest ComboBox info that it read.


My goal:
I want it to read (and write) each row at a time. Meaning it will get columns 1-4 (normal cells) and will get column5 (jComboBox) and write it to a file as the first line. And continue to do so with each line.

I know its a problem with how my loops are set up, however I'm not quite sure how to get it to read it …

KirkPatrick 28 Junior Poster

I'm surprised there hasn't been a reply yet, perhaps there will be a reply for my next question.

I'm wondering how I would go about opening a url with a different proxy per url?

KirkPatrick 28 Junior Poster

Alright well I decided I wanted to widen my learning a bit with java and decided I was going to write a program that had to do with networking side of things.

It took me a little bit of time to come up with something, so I asked my friend and he had an idea for what I should do. That being said, I have a few questions. I'll begin by stating what I want to do and then ask the questions.

The tutorial I have read up on is located at:

http://java.sun.com/javase/6/docs/technotes/guides/net/proxies.html

Seems pretty straight forward, which is why I have chosen it.

My friend has a site where he is testing who connects to his site, downloads which files, and at specific times. So he asked if I would write something to help him test it. I agreed as it should be a pretty good learning experience. I have little knowledge on proxies, from what I understand they allow a person to temporarily use another ip address which is what he is looking for. So from what my friend told me, I'm wanting to do the following...

I'm wanting to:

  • URL = textfield1.getText();
  • Open a ProxyList.txt
  • Check for Proxy type and whether its a good or bad proxy
  • If proxy is good, add to an array (so it can be written to a new file later)
  • Change proxy if proxy can't connect after 2 attempts
  • Change proxy if download was …
KirkPatrick 28 Junior Poster

Sorry for making another post, but its due to an error in the previous one and it not allowing me to edit the post.

In my previous post and code, I have:

JComboBox box = (JComboBox)myColumn.getCellEditor().getTableCellEditorComponent(jTable1, null, false, 0,0);

That was a mistake on my part, I actually have:

JComboBox box = (JComboBox)myColumn.getCellEditor().getTableCellEditorComponent(jTable1, null, false, 0,5);

I'm still having problems and I'm not sure why its not picking things up. I went ahead and put a print statement on 'box.getItemCount()' and its returning 0. The comboBox is populated so it shouldn't be giving me that.

Once again sorry for the triple post, however I didn't want you getting thrown off by a simple typo.

*Is there a reason we are not allowed to edit posts after a certain amount of time?*

KirkPatrick 28 Junior Poster

Okay I have messed with the code a bit, not really progress but at least I have separated the loops, added commentary to help clarify what I'm doing, and am actually getting some output.

Here is what my code looks like now:

private void SaveCsvActionPerformed(java.awt.event.ActionEvent evt) { 

	//Table Model
	javax.swing.table.DefaultTableModel tableModel = (javax.swing.table.DefaultTableModel)jTable1.getModel();

	//ComboBox + Default Editor
        javax.swing.JComboBox comboBox = new javax.swing.JComboBox();
        TableColumn myColumn = jTable1.getColumnModel().getColumn(6);
        myColumn.setCellEditor(new DefaultCellEditor(comboBox));
        JComboBox box = (JComboBox)myColumn.getCellEditor().getTableCellEditorComponent(jTable1, null, false, 0,0);

        try {
	    //Start CSV Writer to write the header to myFile.csv
            com.csvreader.CsvWriter writer = new com.csvreader.CsvWriter("C:\\myFile.csv");
            writer.writeRecord(new String[]{"Column 1, Column 2, Column 3, Column 4, Column 5"});

	    //Set strings null so that they can be referred to outside of the loops
            String column1 = null;
            String column2 = null;
            String column3 = null;
            String column4 = null;
            String column5 = null;

	    //Get the info in the first 4 columns
            for(int i = 0; i< tableModel.getRowCount(); i++) {
                    column1 = (String) tableModel.getValueAt(i, 1);
                    column2 = (String) tableModel.getValueAt(i, 2);
                    column3 = (String) tableModel.getValueAt(i, 3);
                    column4 = (String) tableModel.getValueAt(i, 4);
            }
		    
		    //Get column 5 which contains jComboBox, get all values and set to a string and print to screen
                    for (int h = 0; h < box.getItemCount(); h++) {
                                column5 = (String) box.getItemAt(h);
                    }

	    //Create String[] so that we can write to file and check it with print statement
            String[] abc = new String[] { column1, column2, column3, column4, column5 };

	    //Write String[] abc to myFile.csv
            writer.writeRecord(new String[] { column1, column2, column3, column4, column5});

	    //Print out …
KirkPatrick 28 Junior Poster

Okay well you're example shows how you read all the values at each index inside the jComboBox, assuming that the comboBox is the only column.

Well my table has 4 other columns in front of that column that has the jComboBox.

I am looping through my table to get each row. While looping through each row, I also have to loop through the jComboBox (and its editor) to get all the values in there.

So I have 5 columns and I am wanting to write them to a file. It looks like this:

Column1 = infoString
Column2 = infoString2
Column3 = infoString3
Column4 = infoString4
Column5 = String array (info thats in jComboBox, not just the one thats selected)

The reason I think mine is having trouble is that I loop through the first 4 columns and on the last one I have to do another for loop to get the jComboBox information. I think that is throwing it off, but I can't end the first for loop because then when writing the information to file I can't access the strings for each row.


Is that a bit more clear? I can elaborate more if needed.

KirkPatrick 28 Junior Poster

I gave your code a test just to see if it was a problem with mine. Yours works, and I think I might know why mine is giving me problems.

I am running two loops because I am trying to write each column down and the last column which has the comboBox.

Here is what my code looks like:

private void SaveCsvActionPerformed(java.awt.event.ActionEvent evt) {     
                                   
        javax.swing.table.DefaultTableModel tableModel = (javax.swing.table.DefaultTableModel)jTable1.getModel();

        javax.swing.JComboBox comboBox = new javax.swing.JComboBox();
        TableColumn myColumn = jTable1.getColumnModel().getColumn(5);
        myColumn.setCellEditor(new DefaultCellEditor(comboBox));
        JComboBox box = (JComboBox)myColumn.getCellEditor().getTableCellEditorComponent(jTable1, null, false, 0,0);

        try {

            com.csvreader.CsvWriter writer = new com.csvreader.CsvWriter("C:\\myFile.csv");
            writer.writeRecord(new String[]{"Column1", "Column2", "Column3", "Column4", "Column5"});

            for(int i = 0; i< tableModel.getRowCount(); i++) {
                    String column1 = (String) tableModel.getValueAt(i, 1);
                    String column2 = (String) tableModel.getValueAt(i, 2);
                    String column3 = (String) tableModel.getValueAt(i, 3);
                    String column4 = (String) tableModel.getValueAt(i, 4);

                    for (int h = 0; h < box.getItemCount(); h++) {
                                String column5 = (String) box.getItemAt(h);

          
                    writer.writeRecord(new String[] {column1, column2, column3, column4, column5});
                }
            }
            writer.close();
        } catch(Exception e) {
            e.printStackTrace();
        }
}

Now looking at that, it looks like having that loop inside the other loop could easily cause problems.

So my question is, how would you loop through the comboBox cell editor and adding that to file right behind the other columns in the table?

KirkPatrick 28 Junior Poster

It says you are trying to add a String to an ArrayList of OneRow objects. You an only add a OneRow or a Collection of OneRows

I found my problem, it is highlighted in bold below:

String firstColumn;
ArrayList<OneRow> restOfTheRow;

Scanner input = new Scanner(new File("myFile"));
ArrayList<OneRow> file1 = new ArrayList<OneRow>();

OneRow theOnlyRowInTheFile = new OneRow();
theOnlyRowInTheFile.firstColumn = input.next();
theOnlyRowInTheFile.restOfTheRow.add(input.next());
theOnlyRowInTheFile.restOfTheRow.add(input.next());
theOnlyRowInTheFile.restOfTheRow.add(input.next());
theOnlyRowInTheFile.restOfTheRow.add(input.next());
theOnlyRowInTheFile.restOfTheRow.add(input.next());

Changed it to:

ArrayList restOfTheRow;

Now to finish my class I would add a second scanner

public class OneRow{
        
        String firstColumn;
        ArrayList restOfTheRow;

        public OneRow() throws FileNotFoundException {

            Scanner input = new Scanner(new File("myFile"));
            ArrayList<OneRow> file1 = new ArrayList<OneRow>();

            OneRow theOnlyRowInTheFile = new OneRow();
            theOnlyRowInTheFile.firstColumn = input.next();
            theOnlyRowInTheFile.restOfTheRow.add(input.next());
            theOnlyRowInTheFile.restOfTheRow.add(input.next());
            theOnlyRowInTheFile.restOfTheRow.add(input.next());
            theOnlyRowInTheFile.restOfTheRow.add(input.next());
            theOnlyRowInTheFile.restOfTheRow.add(input.next());
            
            Scanner input = new Scanner(new File("myOtherFile"));
            ArrayList<OneRow> file2 = new ArrayList<OneRow>();

            OneRow theOnlyRowInTheFile = new OneRow();
            theOnlyRowInTheFile.firstColumn = input.next();
            theOnlyRowInTheFile.restOfTheRow.add(input.next());
            theOnlyRowInTheFile.restOfTheRow.add(input.next());
            theOnlyRowInTheFile.restOfTheRow.add(input.next());
            theOnlyRowInTheFile.restOfTheRow.add(input.next());
            theOnlyRowInTheFile.restOfTheRow.add(input.next());

and then I create the comparison method

public void comparisonMethod(){
           int index = -1;
           for (int i = 0; i < file1.size(); i ++) {
       	       if ((index = file2.indexOf(file1Column1.get(i))) != -1) {
                   writer.writeRecord(new String[]{ itemApart2, itemB, itemC, item1part2, item2, item3 });
               }
              index = -1;
           }
       }

Does that sound correct?

KirkPatrick 28 Junior Poster

Okay then I had the right idea about how to go about setting it up (although slightly different source since I didn't use Scanner).

However, I still ended up with the same problem while trying your code. Where it doesn't want to recognize the .add method.

cannot find symbol
symbol: method add(java.lang.String)
location: class java.util.ArrayList<filelocation.OneRow>
add(OneRow e)
add(int index, OneRow element)
addAll(Collection< ? extends OneRow> c)
addAll(int index, Collection< ? extends OneRow> c)

Do you know what could be the problem?

KirkPatrick 28 Junior Poster

Are you sure you're looking at http://java.sun.com/j2se/1.4.2/docs/api/java/util/ArrayList.html ? It's possible that you have used the wrong import statement, it should be import java.util.ArrayList. And I typed the code up in this thread, I never compiled it.

I have the correct import, what I think it is, is that I don't fully understand how the class OneRow works.

Here is what is showing next to all the Strings I want to add into my ArrayList:

cannot find symbol
symbol: method add(java.lang.String)
location: class java.util.ArrayList<filelocation.OneRow>

Here are the options it gives me:

add(OneRow e)
add(int index, OneRow element)
addAll(Collection< ? extends OneRow> c)
addAll(int index, Collection< ? extends OneRow> c)

Do you mind explaining a little bit more about the OneRow class, just so I can get a better understanding? At first it seemed pretty basic with the way that you had explained it, but now I'm not quite sure how its supposed to work.

For the comparison method, it seems like I forgot a parenthesis. It should be:

if ((index = file2Column1.indexOf(file1Column1.get(i))) != -1)

For future reference, a good way to check that is to count the opening parens first, then go back and count the closing parens. The way the computer probably checks this is by pushing any open parens on a stack, then popping an open parens every time it sees a closed parens.

Ah, yeah I had noticed that there was a mismatch in the number of parenthesis. However, …

KirkPatrick 28 Junior Poster

Alright I didn't have a lot of time to work on this today, however I had a brief 10 minutes to try it out and see how the outcome would be.

By the time I got to changing the code around and working with the methods that you showed, however I am having some problems.

Your comparison method tells me that it is having incompatible types, its giving a boolean and wanting an int.

public void comparisonMethod(){
int index = - 1;
for (int i = 0; i < file1Column1.size(); i++){
   if ((index = file2Column1.indexOf(file1Column1.get(i)) != -1){
      printTheStuff(index, i);
   }
  index = -1;
}
}

Then when trying to add strings to the arraylist its showing that there isn't an add method for it.

ArrayList<OneRow> file1Column1 = new ArrayList<OneRow>();
ArrayList<OneRow> file2Column1 = new ArrayList<OneRow>();


//read file, split line of info into columns, and assign strings to each column here

//add split columns to arraylist
file1Column1.add(itemA);
file1Column1.add(itemB); 
etc
etc

I've had an off morning so that may be why I'm not seeing what I'm missing as I'm sure its something obvious. Hope you don't mind pointing me in the right direction again because when I read it, the logic made sense until trying to make it into code.

KirkPatrick 28 Junior Poster
public class yourBeanInfoClassIForgotTheNameOf{
ArrayList<String> file1Column1 = new ArrayList<String>();
ArrayList<String> file2Column1 = new ArrayList<String>();

//Blah blah blah, your methods go here
}
public class OneRow{
//This is the String from the first column
String firstColumn;
//This is the remainder of the row
ArrayList<String> restOfTheRow;
}

For example, if you had the following file:

book, chapters, pages
phone, plastic, wires
ipod, music, video

You'd have three OneRow objects.
First OneRow object: firstColumn = book
restOfTheRow holds chapters and pages
Second OneRow object: firstColumn = phone
restOfTheRow holds plastic and wires.
Third OneRow object: firstColumn = ipod
restOfTheRow holds music and video.

I have read over your post more thoroughly here and I am wondering if this will work when we won't know what the data is in the first column. As that was just an example of data that could be stored in the file.

I assume thats where this comes in?

public class OneRow{
//This is the String from the first column
String firstColumn;
//This is the remainder of the row
ArrayList<String> restOfTheRow;

@Override
public boolean equals(Object obj){
    //I'll let you implement this method, in here you'd want to compare two OneRow Objects for equality. Since you want to compare columns, you'd just want to test if this (this.) OneRow object's firstColumn is equal to Object obj's firstColumn. If so, you return true, otherwise, return false. 
}
}

Is that where I have it decide whether the firstColumn and OneRow objects belong together for …

KirkPatrick 28 Junior Poster

Sorry for the late response on this part, I haven't had the chance to continue working on this part till today. I went ahead and tried what you were saying and the output comes out blank.

My code isn't the exact same as yours because I already have the table and column so I will go ahead and show you my source (in case I messed it up)

javax.swing.JComboBox comboBox = new javax.swing.JComboBox();
                    TableColumn myColumn = jTable1.getColumnModel().getColumn(5);
                    myColumn.setCellEditor(new DefaultCellEditor(comboBox));
                    JComboBox box = (JComboBox)myColumn.getCellEditor().getTableCellEditorComponent(jTable1, null, false, 0,0);

                    for (int i = 0; i < comboBox.getItemCount(); i++) {
                        //System.out.println(comboBox.getItemAt(i));
                                String allItems = (String) comboBox.getItemAt(i);

            writer.writerRecord(new String[] { item1, item2, item3, allItems });
}

Both printing it and adding it to file returned blank. I'm not quite sure why as the logic sounds correct. I hadn't even thought about getting the cell editor for the column. Didn't even know much about it until ezzaral mentioned it.

Am I missing something? Or does it also return blank for you?

KirkPatrick 28 Junior Poster

Very helpful reply BestJewSinceJC. Right now I'm testing with my comparison (i got it working, there was a minor mistake in my code that i didn't notice when searching for the end of my headers).

I am going to continue testing to see if mine will work. Once I test it thoroughly I am also going to test your example. The way you have explained it, seems cleaner.

Major thanks for your time and explanation there bud.

Just a thought: if you store the data in two HashTables, using the first column in each of the two files as keys and the rest of the columns as the values, then finding matching entries becomes trivial...

I had brought this up in a thread earlier and I didn't quite understand how to implement it.


One problem still remains though, when I split my text file lines I have to split it into 3 columns. Sometimes I have less than 3 columns and it will throw an arrayoutofbounds exception. Is there a way to fix this?


I'll report back on my findings between the two ways of comparing the files when I'm done testing.

KirkPatrick 28 Junior Poster

Yes the output is working now, however some of what the output doesn't seem to be right. I'm thinking my comparison might have been written incorrectly. (check above post to see)