KirkPatrick 28 Junior Poster

There is a site that explains web crawlers a bit that I came across a few weeks back:

http://andreas-hess.info/programming/webcrawler/index.html

Hope it is helpful

KirkPatrick 28 Junior Poster

I have a Tcp Client (in Java) and a Tcp Server (in Groovy) and I am having problems getting the Client to communicate properly. I believe the issues involve my client not being able to send information to the server. (My assumption is the problem is somewhere near line 32 in my client)

My server works fine when accessed by telnet, just not with my java client.

Client:

public class Client {

    Socket requestSocket;
    String message;
    BufferedReader in;
    BufferedWriter out;

    Client() {


    }

    void connect(String host) {

        String command = "ip";

        try {
            requestSocket = new Socket(host, 2000);
            System.out.println("Connected to localhost in port 2000");

            in = new BufferedReader(new InputStreamReader(requestSocket.getInputStream()));
            out = new BufferedWriter(new OutputStreamWriter(requestSocket.getOutputStream()));

            while(true) {
                message = in.readLine();
                System.out.println("server>" + message);
               
                if(command != null) {
                    sendMessage(command);
                    command = null;
                }

            }
        }
        catch(UnknownHostException unknownHost) {
            System.err.println("You are trying to connect to an unknown host!");
        }
        catch(IOException ioException) {
            ioException.printStackTrace();
        } finally {
            try {
                in.close();
                out.close();
                requestSocket.close();
            }
            catch(IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }

    void sendMessage(String msg) {
        try {
            out.write(msg);
            out.flush();
            System.out.println("client>" + msg);
        }
        catch(IOException ioException) {
            ioException.printStackTrace();
        }
    }

    public static void main(String args[]) {

        Client client = new Client();
        client.connect("localhost");


    }

}

Server:

//variables
def serialNo
def ipAddress
def machineName
def operatingSystem

server = new ServerSocket(2000)

println("Waiting for connection");

while(true) {
	server.accept() { socket ->
		socket.withStreams { input, output ->
				
			w = new BufferedWriter(new OutputStreamWriter(output))
			String message = "Connection was successful"

			r = new BufferedReader(new InputStreamReader(input))
			

			while(true) {
							
				if(message != …
KirkPatrick 28 Junior Poster

I find it interesting that the posts that were marked +rep and helpful were ones that didn't have anything to do with the topic but rather blasted the OP. I agree with some of the remarks that were made about the improper english. That type of typing/use of language is more of a hassle than its worth to help the OP out for. But I don't think those posts should be marked as helpful.

The helpful posts came from javaAddict and Kontained (i went ahead and marked them as helpful).

@hina hasan
The more effort and respect you show to the members that you are asking for help, the more help they are willing to offer ;)

KirkPatrick 28 Junior Poster

I'm a bit late on replying to the thread but so far it looks like I have it working the way I want it to. If I have anymore problems, I'll post back and hopefully you'll reply.

Do you see any way I could improve my code?

Client:

public class Client {

    Socket requestSocket;
    BufferedWriter out;
    BufferedReader in;
    String message;


    Client() {


    }

    void run() {
        try {
            requestSocket = new Socket("localhost", 1960);
            System.out.println("Connected to localhost in port 1960");

            in = new BufferedReader(new InputStreamReader(requestSocket.getInputStream()));
            out = new BufferedWriter(new OutputStreamWriter(requestSocket.getOutputStream()));

            do {
                try {
                    message = in.readLine();
                    System.out.println("server>" + message);
                    sendMessage("dir");
		    sendMessage("exit");
                }
                catch(ClassNotFoundException classNot) {
                    System.err.println("Data received in unknown format");
                }
            } while(!message.equals("exit"));
        }
        catch(UnknownHostException unknownHost) {
            System.err.println("You are trying to connect to an unknown host!");
        }
        catch(IOException ioException) {
            ioException.printStackTrace();
        } finally {
            try {
                in.close();
                out.close();
                requestSocket.close();
            }
            catch(IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }



    void sendMessage(String msg) {
        try {
            out.write(msg);
            out.flush();
            System.out.println("client>" + msg);
        }
        catch(IOException ioException) {
            ioException.printStackTrace();
        }
    }



    public static void main(String args[]) {
        Client client = new Client();
        client.run();
    }


}

Server:

//variables
def serialNo
def ipAddress
def hostName
def operatingSystem
def test

server = new ServerSocket(1960)
println("Waiting for connection");
while(true) {
	server.accept() { socket ->
		socket.withStreams { input, output ->
			
			w = new BufferedWriter(new OutputStreamWriter(output))
			String message = "Connection was successful"
			w.writeLine(message)
			w.flush()

			r = new BufferedReader(new InputStreamReader(input))
			String a = r.readLine()

	
			if(a=="serial") {
				getSerialNo();
			} else if(a=="dir") {
				getTest();
			} else if(a=="os") {
				getOperatingSystem();
			} else …
KirkPatrick 28 Junior Poster

First of all, thank you for the reply masijade.

since your groovy script is not creating an ObjectOutputStream for your java program to read your ObjectInputStream fails.

Thank you for clearing that up. This seems like it is what causes the issue.

Why are you even attempting to open any kind of InputStream on the Java side if your Groovy script is not sending anything?

Edit: Okay, I see you are writing from the groovy side (although it is sometimes w and sometimes writer and neither, as far as I can see, is ever defined).

Basically my script is just supposed to get commands from the java program. In my test I would send a simple string "dir" and it would be sent to the script, and the script would then check what it should do based on the text command that was sent. For example, when 'dir' was sent, it would go to the command prompt and print out a dir of the c drive.

Now my test examples worked because it was from command prompt to command prompt. So I'll need to modify the script to handle objects (if I understand your response correctly)

Sorry for the confusion on the writing from the groovy side, I originally had it as 'w' and then changed it to 'writer' but had issues and right before posting I changed it back to 'w' but missed changing the 'writer.close()' to 'w.close()'

My script has to act as …

KirkPatrick 28 Junior Poster

I seem to be having an issue with a program I am creating. It should be a simple program that sends commands from a Java program to a Groovy script (whether the script be on the same computer or another on the network) but I am running into some problems.

I have found a very simple TCP/IP client snippet and am trying to get it to access a groovy script I have created that is listening on port a certain port.

Before implementing this in my program, I did a simple test with telnet. It came back with positive results so I went ahead and tried it out. Unfortunately I have received the following exception: java.io.StreamCorruptedException: invalid stream header: 57686174

Here is my Java program source:

public class Client {

    Socket requestSocket;
    ObjectOutputStream out;
    ObjectInputStream in;
    String message;


    Client() {


    }

    void run() {
        try {
            requestSocket = new Socket("localhost", 1960);
            System.out.println("Connected to localhost in port 1960");

            out = new ObjectOutputStream(requestSocket.getOutputStream());
            out.flush();
            in = new ObjectInputStream(requestSocket.getInputStream());

            do {
                try {
                    message = (String)in.readObject();
                    System.out.println("server>" + message);
                    sendMessage("dir");
                }
                catch(ClassNotFoundException classNot) {
                    System.err.println("Data received in unknown format");
                }
            } while(!message.equals("exit"));
        }
        catch(UnknownHostException unknownHost) {
            System.err.println("You are trying to connect to an unknown host!");
        }
        catch(IOException ioException) {
            ioException.printStackTrace();
        } finally {
            try {
                in.close();
                out.close();
                requestSocket.close();
            }
            catch(IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }



    void sendMessage(String msg) {
        try {
            out.writeObject(msg);
            out.flush();
            System.out.println("client>" + msg);
        }
        catch(IOException ioException) {
            ioException.printStackTrace();
        }
    }



    public static void main(String …
KirkPatrick 28 Junior Poster

I am not sure this will work with SCSI but you could try.
It is a big i not a small L after hdparm -
sudo hdparm -I /dev/sda

( -I gives you detailed/current information directly from drive)

You can also search for scsi_id commands but they do not work on my computer so I can not help you with them.

Yeah I had tried hdparm at the time that I had tried sdparm as well. Also scsi_id didn't work either. I had tried all three and was searching for alternatives, but after numerous pages through google I couldn't find much about it.

Thanks for your help sneaker, for now I think I'll have to find a way of installing sdparm.

I'll mark this solved for the time being

KirkPatrick 28 Junior Poster

Thanks bud I'll check out the man pages, anyone know anything about question #1?

KirkPatrick 28 Junior Poster

Thanks for the help.

I'm not sure how itunes works but I'm thinking what you could do is create a jLabel and have a left mouse click play the song and a right click on the mouse would give you options.

So maybe add a mouse listener to the jLabel
and if MouseEvent.button1 -> play song
else if MouseEvent.button2 -> option to get image


Not sure if that is really helpful, but it's a shot in the dark

KirkPatrick 28 Junior Poster

Hey guys, I'm fairly new to using linux however I need to know a few things. (I'm very aware there are examples on the web for most of these, but I want to know how you guys personally prefer to go about these)

1) Find hard drive serial (SCSI) without the use of sdparm
2) Find Ip Address of the current machine
3) Find the machine name of the current machine
4) Find the operating system of the current machine


My findings for this are:
1) (unsure)
2) ifconfig | grep "inet addr"
3) hostname
4) uname -a


Do you guys have better ways of finding these things? Also are my findings correct?

KirkPatrick 28 Junior Poster

It would make the return type be the return type of the last method call in the chain. You have created an object and called a method on it. It's no different than calling a method on a reference to that object that was created previously.
You InfoObject panel is still going to need to respond to some event like checkbox action performed, mouse clicked, etc. to know when to fire the selection change.

This was the example you gave for the mouse click

addMouseListener(new MouseAdapter() {
    @Override
    public void mouseClicked(MouseEvent e) {
        setSelected(!selected);
        if (selected) {
            fireSelectionChanged();
        }
    }
});

So if I wanted to just do it by checkbox, would I be able to just do the following:

public void itemStateChanged(ItemEvent e) {
        if(jCheckBox1.isSelected()) {
            fireSelectionChanged();
        } 
    }

Then would I set the backgrounds in my fireSelectionChanged() method, or would it be better to do it in the itemStateChanged instead?

Thanks for all your help Ezzaral and gangsta1903. You both have been quite helpful.

KirkPatrick 28 Junior Poster

You have chained the constructor with the .add() call, so the end result is a return type of the add() function - which is void. Construct it first, then add the listener.

Interesting, this isn't very important, but would that always make the return type void?

Also, with implementing this interface, would I be able to get rid of my focus listeners and item listeners that I added previously?

I have left the checkbox in as I thought it was a good suggestion. I'm just wondering where setting the InfoObjects background would come into play with the interface. Would I add it in the fireSelectionChanged method?

KirkPatrick 28 Junior Poster

The declaration looks just fine to me with the exception of that spelling difference.

You know what, I forgot to add the import for it.

However, now it is saying that I have incompatible types. It's expecting an InfoObject and we are giving it a void. Does this sound right?

Once again, it works for:

ndbo.addInfoObjectSelectionListener(this);

But it won't work for:

ndbo = new InfoObject(string1, string2, arraylist).addInfoObjectSelectionListener(this);
KirkPatrick 28 Junior Poster

Spelling? implements InfoSelectionlistener If your class implements that interface, then its reference can be passed as a parameter to a method expecting that type.

In my example on the forum, you are correct I did not capitalize the 'L'. However in my code, I copied and pasted to make sure it was the same spelling and case sensitive. I'm still not sure why it won't accept 'this' as a parameter.

Did I add the implements InfoSelectionListener in the wrong place? It does need to be on the class and not the InfoViewer constructor or ReadFile function correct?

The non-public API warning thing is most likely a matter of how you declared the interface. You probably didn't declare it public, but it's being used in a public manner.

Good call, I didn't declare the interface as public.

KirkPatrick 28 Junior Poster

>When attempting to implement InfoSelectionListener it tells me that the types are different.
Your InfoViewer just needed to implement InfoSelectionListener, then it would have allowed "this" as the parameter.

Correct, without copying all the code, I'll try and show you what I did. In the InfoObject I added the code you provided right above my getters. The InfoViewer is where the implementing is an issue

InfoViewer:

public class InfoViewer extends javax.swing.JPanel implements InfoSelectionlistener {

	//some variables declared here, omitted to shorten the example

	public InfoViewer() throws FileNotFoundException, IOException {

		//check os 
		initComponents();
		ReadFile(); //reads txt file to grab values (also adds ndbo)

	}

	
	public void ReadFile() {

		//declare variables
		//read txt file and grab values
		
		//attempt to add InfoSelectionListener
		ndbo.new(string1, string2, arraylist).addInfoSelectionListener(this);
		//Netbeans cannot find symbol
		//Symbol: addInfoSelectionListener(InfoViewer)
		//location InfoObject

		//add ndbo to arraylist for writing
		//close txt file reader
		//iterate through arraylist and add InfoObjects to panel
		//catch exceptions

	} 

}

My assumption is that it might be due to my ndbo being in my ReadFile() function?

Just a side note, on addInfoSelectionListener it is also telling me that I am 'Exporting a non-public type through a public API'

As far as the rest, I didn't really follow what you were trying to do with the ArrayList.
With the checkbox, you really only need to add a method to InfoObject like

public boolean isSeletected(){
   return chkSelected.isSelected();
}

I was checking if the checkbox was checked, if it was it would set the InfoObject's …

KirkPatrick 28 Junior Poster

and your viewer would just need to implement the InfoSelectionListener interface and add itself as a listener when you created the InfoObject items

ndbo.addInfoSelectionListener(this);

When attempting to implement InfoSelectionListener it tells me that the types are different.

Required: InfoObject.InfoSelectionListener
Found: InfoViewer

So I had to recreate the method for addInfoSelectionListener by casting it like so:

public void addInfoObjectSelectionListener(InfoViewer listener) {
        listeners.add((InfoObjectSelectionListener) listener);
    }

Then in my Viewer I could only apply this method to ndbo and not my InfoObject(string1, string2, arraylist1)

Will that cause an issue?

Before reading your post, I had something really funky set up (although I was just testing things out):

First I implemented an ItemListener on my InfoObject and created my handling for it:

public void itemStateChanged(ItemEvent e) {
        isFocused = true;
        if(jCheckBox1.isSelected()) {
            jCheckBox1.setBackground(rowSelected);
            jTextField1.setBackground(rowSelected);
            jTextField2.setBackground(rowSelected);
            jTextField3.setBackground(rowSelected);
            jTextField4.setBackground(rowSelected);
            jTextField5.setBackground(rowSelected);
            jTextField6.setBackground(rowSelected);
            jCheckBox1.getParent();
            System.out.println(jCheckBox1.getParent());
        } else {
            jCheckBox1.setBackground(Color.WHITE);
            jTextField1.setBackground(Color.WHITE);
            jTextField2.setBackground(Color.WHITE);
            jTextField3.setBackground(Color.WHITE);
            jTextField4.setBackground(Color.WHITE);
            jTextField5.setBackground(Color.WHITE);
            jTextField6.setBackground(Color.WHITE);

        }
    }

Then I created a getter for the ArrayList I was going to compare with the original ArrayList:

public ArrayList getSelectedData() {
        if(jCheckBox1.isSelected()) {
            jCheckBox1.getParent();
            selectedData.add(jCheckBox1.getParent().toString());
            } else {
            selectedData.remove(jCheckBox1.getParent().toString());
        }
        return selectedData;
    }

I didn't have the chance to fully think through the logic of it as I ran into some issues and would probably have to add in some if/else statements with some math in case the user clicked the checkbox multiple times.

As you can see, this is all new stuff I've been working with and my logic may …

KirkPatrick 28 Junior Poster

The easiest thing to do would be just add a checkbox to the panel to set a boolean "selected" property on the object. That would allow multiple selection as well.

Here's an article on MVC if you care to read more on that topic: http://java.sun.com/developer/technicalArticles/javase/mvc/?intcmp=3273#3

Just to clear this up, are you suggesting I add a JCheckBox to the InfoObject, or add a JCheckBox to the side on the panel when I add each InfoObject?

KirkPatrick 28 Junior Poster

you considered that "highlighting" of the button as a focus event...
in fact, its true. focusing can be gained by mouse and keyboard.

Do you want to do it when it gains focus or when it is clicked?

you can read following tutorials to learn the differences between event listeners, and also how you can use them.

http://java.sun.com/docs/books/tutorial/uiswing/events/index.html

Correct when it gains focus (in my case the user clicks on a textfield of the InfoObject) I want to be able to click my button "Delete Row" and get rid of that information from the ArrayList and jPanel.

However, below, Ezzaral confirmed that the focus has changed as soon as I click "Delete Row"

I'll start reading from the link you have provided me with. I'll have to find a listener than will keep that ViewObject focused while clicking the "Delete Row" button.

The easiest thing for you to do is loop the InfoObjects in your array to find the "selected" one and remove it.

Can you elaborate on how it would find which one is "selected". That the issue I'm trying to resolve, is how to tell that specific object is currently selected (at least from the arraylists perspective)

There is a lot you could do to add listeners, models, etc to make this more MVC, but it would require a decent amount of extra work because your UI objects are your data objects at this point.

Would you mind elaborating on this? …

KirkPatrick 28 Junior Poster

I thought your textFields had action listeners but your InfoObjects didnt. And I told you that you could access your InfoObject in the actionperformed methods of your textFields by using getParent() method.

Lets clear the situation:
- You want to remove a component from another component.
- Of course, you can do it upon events. An event can be clicking, focusing, resizing, moving, etc ....
- So, if you want to catch these events, you have to add corresponding listeners to your components.
- If a component does not listen to any events, how can you catch it?
- Thus, you have to add listeners.

#
//grab the info and put it in a new info object
#
ndbo = new InfoObject(string1, string2, newLists);
#
 // you created an InfoObject, now add action listener for example
ndbo.addActionListener(yourActionListener);
// or focus listener, add what event you want to listen
ndbo.addFocusListener(yourFocusListener);
#
//grab info from info object and store for writing to file
#
list.add(ndbo);

Correct, I attempted to add Listeners to my InfoObjects but some of them are added in a void function. What would I change my return type to?

Also, I just realized, upon clicking a button doesn't the focus change? Ie. My InfoObject is focused (and highlighted) but when I click the "Delete Row" button it now becomes the focus and can't delete the row?

Also I took your example above, added a getter into the other class where the text …

KirkPatrick 28 Junior Poster

I don't believe that is possible either. My reasoning being that the jTextField is not accessible from the other class.

InfoObject:

  • contains the jTextFields
  • holds the FocusListener

InfoViewer:

  • contains the InfoObjects
  • when a textfield is clicked, all textfield's backgrounds are colored
  • each InfoObject is added either by being read from file (void function) or from the user which is then added in by a click of a button

For the way you show above, I believe I would need access to each textfield. Forgive me if I'm wrong, I'm a bit confused about it.

I'll put the source up and leave comments next to them, maybe this will help.


InfoObject (same as last post):

public class InfoObject extends javax.swing.JPanel implements FocusListener {

  private String string1;
  private String string2;
  private ArrayList newList;

  //add to combobox after getting
  private String newList1;
  private String newList2;
  private String newList3;
  private String newList4;
  private String newList5;


  Boolean isFocused;

  Color rowSelected = new Color(198,226,255);

    /** Creates new form InfoObject */
    public DatabaseObject(String string1, String string2, ArrayList newList) {
        initComponents();

        this.string1 = string1;
        this.string2 = string2;
        this.newList = newList;

        for (int i = 0; i < newList.size(); i++){
           jComboBox1.addItem(newList.get(i));
        }

        jTextField1.setText(string1);
        jTextField2.setText(string2);
        jTextField1.addFocusListener(this);
        jTextField2.addFocusListener(this);
    }

  public String getstring1() {
    return this.string1;
  }

  public String getstring2() {
    return this.string2;
  }


  public ArrayList getoComboBox() {
      return this.newList;
  }

  public boolean isFocused() {
      return isFocused;
  }


    public void focusGained(FocusEvent e) {
        isFocused = true;
        jTextField1.setBackground(rowSelected);
        jTextField2.setBackground(rowSelected);
        jTextField3.setBackground(rowSelected);
        jTextField4.setBackground(rowSelected);
        jTextField5.setBackground(rowSelected); …
KirkPatrick 28 Junior Poster

I dont know how and where you use deleteRowActionPerformed.

But as far as I see, this is what you are looking for.

You can find the object which causes(has) the event. If you wanna find the InfoObject on focus, then you should access the InfoObject focused by the following line inside of your event handling method.

// now you get the InfoObject which InfoObject focused            
        InfoObject ndbo = (InfoObject) evt.getSource();

DeleteRowActionPerformed is my button. I'm going to put the code in it when I figure out which code is necessary.

Psuedocode:

if(object is selected) {
   remove object from list
   remove object from panel
}

Can you elaborate on your example? I currently don't have an event listener on the object itself. I have a focus listener on the textfields of the object. The listener only changes the background colors and returns a boolean true or false.

I don't seem to follow what you are suggestion, maybe I'm looking at it from the wrong angle.

I think you are suggesting that I add an focus listener to each InfoObject I add?

KirkPatrick 28 Junior Poster

If you put the code, I can help. If I cant, maybe others can help.

Thank you for the help thus far, I'll post the source (or what's needed of the source)


InfoObject:

public class InfoObject extends javax.swing.JPanel implements FocusListener {

  private String string1;
  private String string2;
  private ArrayList newList;

  //add to combobox after getting
  private String newList1;
  private String newList2;
  private String newList3;
  private String newList4;
  private String newList5;


  Boolean isFocused;

  Color rowSelected = new Color(198,226,255);

    /** Creates new form DatabaseObject */
    public DatabaseObject(String string1, String string2, ArrayList newList) {
        initComponents();

        this.string1 = string1;
        this.string2 = string2;
        this.newList = newList;

        for (int i = 0; i < newList.size(); i++){
           jComboBox1.addItem(newList.get(i));
        }

        jTextField1.setText(string1);
        jTextField2.setText(string2);


        jTextField1.addFocusListener(this);
        jTextField2.addFocusListener(this);

        
    }

  public String getstring1() {
    return this.string1;
  }

  public String getstring2() {
    return this.string2;
  }


  public ArrayList getDccComboBox() {
      return this.newList;
  }

  public boolean isFocused() {
      return isFocused;
  }



    public void focusGained(FocusEvent e) {
        isFocused = true;
        jTextField1.setBackground(rowSelected);
        jTextField2.setBackground(rowSelected);
        jTextField3.setBackground(rowSelected);
        jTextField4.setBackground(rowSelected);
        jTextField5.setBackground(rowSelected);
        jTextField6.setBackground(rowSelected);
        System.out.println("true");
    }

    public void focusLost(FocusEvent e) {
        isFocused = false;
        jTextField1.setBackground(Color.WHITE);
        jTextField2.setBackground(Color.WHITE);
        jTextField3.setBackground(Color.WHITE);
        jTextField4.setBackground(Color.WHITE);
        jTextField5.setBackground(Color.WHITE);
        jTextField6.setBackground(Color.WHITE);
        System.out.println("false");
    }

}

My jPanel only contains a function inside the class which ill post below (along with the soon to be delete button):

public void ReadFile() {

        String string1, string2, newList1, newList2, newList3, newList4, newList5;

        try {
            com.csvreader.CsvReader reader = new CsvReader(computerCsvPath);
            reader.readHeaders();
            while(reader.readRecord()) {

                ArrayList allList = new ArrayList();

                //get the data from file
                string1 = reader.get("Title1");
                string2 = reader.get("Title2");
                newList1 = reader.get("Title3");
                newList2 = reader.get("Title4");
                newList3 = …
KirkPatrick 28 Junior Poster

I agree, I just need access to the object so I can remove it from the arraylist and the panel if need be.

If you would like code I can provide it. It is actually quite simple code. I just question on how to go about accessing the specific object that is selected for the time being.

KirkPatrick 28 Junior Poster

The issue with that solution is that I have so many InfoObjects being added that I don't name them with numbers after it.

It looks like so (psuedocode):

for each line in text file {
            iObject = new InfoObject(param1, param2, array)
        }

Which is why I added the isSelected boolean to the object. When it is highlighted I would like to be able to have some way of knowing which object in the arraylist that it is so I can remove it.

So I figured I had to get the index of the InfoObject and then I can go about removing it.

I appreciate the help, but I don't think that will work for what I'm attempting to do. Any other ideas?

KirkPatrick 28 Junior Poster

I have a question on how to get the index of a selected object. I'll briefly explain my project to help get a better understand of what I'm doing.

I have created a simple object (named InfoObject) which is made up of 2 jTextfields and 1 jComboBox. I have added focusListeners to the textfields. When a jTextField is clicked/focused it sets the background to a specified color (making it obvious that the object of information has been selected) Also, when the object is focused it sets a boolean to true, when it is no longer focused, the boolean is returned to false.

I then have a separate class containing my jPanel that adds an InfoObject to the panel upon reading a file and upon a users input. I also add each object to an arraylist. (ArrayList<InfoObject>)

My Question:
Is there a way to get the index of the InfoObject when it is focused/clicked? My goal is that when the object is focused, I'll have the opportunity to click a button which removes the object from the jPanel and the ArrayList so that when I save the information it doens't have any old information in it.


I can provide source or extra details if need be. Looking forward to replies. Thanks to anyone and everyone who offer advice on the matter

KirkPatrick 28 Junior Poster

I'm not quite sure what your issue is, the program you wrote seems to do what is requested.

Maybe I'm reading it wrong, but you are wanting it to do the following:

  • Read input
  • Throw exception if its not a number
  • Upon 2 exceptions quit asking for input
  • Add numbers to equal sum
  • Exit

If you are wondering why it won't get information after entering two wrong answers in a row, its because you set more to false instantly and it stops asking for more numbers when it is false (exits and prints out the sum)


I commented some of your code to hopefully help you understand why you can't ask for next number

while (more) { //when more is true, do the whole try block
            try {
                num = scan.nextFloat();
                System.out.println("Value: " + num);
                sum = sum + num;
            }
            
            catch (InputMismatchException exception) {
                System.out.println("Input Error.  Try again.");
                count++;
                if (count >= 2) {
                    more = false; //more turns false
                }
                num = scan.nextFloat(); //this can't run when it's false because its in the try block
            }
            
        }
        System.out.println("Sum: " + sum);
 }
}

Hope this helped a little

KirkPatrick 28 Junior Poster

Why not go to user control panel and go to edit options and untick the box that allows the site to email you? Seems simpler for one to do rather than having an admin/mod go into the CP and remove every user that complains about it.

Also, you posted it in the wrong section, the correct section would be an admins/mods PM box.

KirkPatrick 28 Junior Poster

Thank you Ezzaral! You've been most helpful. I am very grateful that you commented your code. With a few simple modifications, this code can do exactly what I'll want it to do.

For the font issues, I might have to throw some changes in when the tab/panel is clicked.

I'll have to give this a test run when I get the chance (my desktop that I was doing the coding on crashed this past weeked)

KirkPatrick 28 Junior Poster

Ah alright that makes more sense, thank you for explaining that. I'll have to do a bit of testing to see how it splits the screen devices (if it does at all).

My computer looks like it also puts both my monitor as a single screen device. Which might be an issue later on, since I want to make the jPanel take up the entire second monitor and none of the default monitor.

As for the other questions:

  • How would I grab the information located on the jPanel that I want to display on the second monitor? (is there a quick easy way to duplicate the panel)
  • Would I encounter issues with the fonts? (Seeing as the second monitor will be much larger than the original one)
KirkPatrick 28 Junior Poster

I feel like I'm a bit over my head on this one. I have been reading the documentation for a good 45 minutes and can't make a whole lot of sense of it.

My assumptions at this moment is that I want to get screen devices and pick which one I am wanting to display on the second monitor? If that is so, I must be doing something wrong because I get every GraphicDevice and throw it onto a JFrame and each of them are blank. (I was testing out the example they provided to see what the results would be)

Can you or anyone who might understand this area perhaps explain how it works a bit? I have been searching the net for the past 30 minutes and not finding much. I have been searching: GraphicsEnvironment, GraphicsDevice, and GraphicsConfiguration. The problem is that the only pages that come up are the API which use terminology I'm not familiar with. Which then leads me to look up the terminology and I can't seem to find any good definitions for some of the terms. (It is kind of a big circle of searching google at this point)

I have multiple questions, but I will hold off on them once I get a solid starting point.

I'll continue reading up on it, thank you for pointing me in the right direction Ezzaral

KirkPatrick 28 Junior Poster

I have a program where my JFrame contains a tabbed pane with 3 tabs, I am wanting to make it so that when tab1/jpanel1 is doubled clicked it displays the contents of the JPanel on the second monitor. In my case the second monitor will be a large plasma screen (42 inch).

I'm not quite sure what I need to read up on or the keywords I should be focusing on, so if anyone knows where I should begin or the keywords that would lead me to what I'm looking for I would appreciate the insight.

KirkPatrick 28 Junior Poster
private void initEntities() {		
                ship=new ShipEntity(this,"spaceinvaders/ship.gif",380,550);
                entities.add(ship);

sorry for being such a bother, but i really want to make this work and fully understand it
thanks a lot for all your help so far.

I believe Ezzaral was saying that you should create a simple .gif file that contains your simple shape instead of changing the other method. So instead of having it draw a rectangle through java, create a rectangle.gif. This will simply replace the ship.gif without having to change more methods than necessary.

@Ezzaral feel free to correct me if I interpreted your response wrong

KirkPatrick 28 Junior Poster

but it is possible to write a keylogger in java?

I haven't done it, but I have seen someone create a program that included one before. It is much more common with other languages as mentioned above.

KirkPatrick 28 Junior Poster

Thank you, my code looks a bit cleaner now.

KirkPatrick 28 Junior Poster

Oh gosh, sometimes I wonder what's going on in my head when I code.

Thank you for pointing that out Ezzaral.


So I would have to create a few extra ints for this then:

int aaa = GridBagConstraints.CENTER;
int bbb = GridBagConstraints.NONE;
int ccc = GridBagConstraints.HORIZONTAL;

then I could go ahead and use these in my function.

KirkPatrick 28 Junior Poster

When I take that function and add int params it tells me it can't find that symbol. For instance:

Function:

public void gridBagControl(Component ob, JPanel p, Insets in, int row, int w_y, int g_x, int fill, int c, int h) {
        GridBagConstraints gridBagConstraints = new GridBagConstraints();
        gridBagConstraints.gridx = g_x;
        gridBagConstraints.gridy = row;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = w_y;
        gridBagConstraints.anchor = GridBagConstraints.c; //can't find symbol
        gridBagConstraints.fill = GridBagConstraints.h; //can't find symbol
        gridBagConstraints.insets = in;
        p.add(ob,gridBagConstraints);
    }

My anchor will always be either CENTER or NONE
My fill will always be HORIZONTAL or NONE

KirkPatrick 28 Junior Poster

Haven't really dealt with this before, but have you tried:

JFrame.HIDE_ON_CLOSE

Not sure if the results will be different. Might have the main JFrame dispose of them both on exit

KirkPatrick 28 Junior Poster

I'm wondering if it is possible to control certain aspects in my function. All my it does is control how an object gets placed on my gui.

I'm wondering if there is a way to control GridBagConstraints.fill and GridBagConstraints.anchor

Function:

public void gridBagControl(Component ob, JPanel p, Insets in, int row, int w_y, int g_x, int fill) {
        GridBagConstraints gridBagConstraints = new GridBagConstraints();
        gridBagConstraints.gridx = g_x;
        gridBagConstraints.gridy = row;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = w_y;
        gridBagConstraints.anchor = GridBagConstraints.CENTER; //want to add CENTER as a param
        gridBagConstraints.fill = GridBagConstraints.HORIZONTAL; //want to add HORIZONTAL as a param
        gridBagConstraints.insets = in;
        p.add(ob,gridBagConstraints);
    }

Just thought I would post and see if anyone knew how to get those to work with the function. They seem to be ints which is what I tried at first however encountered some issues.

Anyways, I'm sure this will be a thread that is solved quickly. In advance, thanks for the help.

KirkPatrick 28 Junior Poster

Count your brackets, chances are you are missing one ;)

KirkPatrick 28 Junior Poster

I'm not quite sure I understand your question exactly, but when you are overriding something there are infinite possibilities depending on what you are wanting to do.

For instance, I have an object and I want to change how toString() works instead of just giving me random information. Lets say I want it to actually print out the information in it with commas between the values. The code would look like so:

@Override
public String toString() {
        StringBuffer b = new StringBuffer();
        b.append(getStringA() + "," + getStringB() + "," + getStringC());
        return b.toString();
    }

To my knowledge no, there isn't only one way to code an override. It really depends on what you want to do with it. You will however need the @Override though.

Now specifically for Overriding .equals() so that it compares objects or values of objects, most code will probably be similar.


(if my post is inaccurate or one feels the need to elaborate feel free to post so, constructive criticism is a great learning tool)

KirkPatrick 28 Junior Poster

I actually started a small html parser not long ago (never did get too specific with it, but was hoping on expanding it)

Just a short snippet I pulled out from the link you are pulling the feed from:

<title>Reclusive author J.D. Salinger dies</title>

<guid isPermaLink="false">http://www.cnn.com/2010/SHOWBIZ/books/01/28/salinger.obit/index.html?eref=rss_topstories</guid>
<link>http://rss.cnn.com/~r/rss/cnn_topstories/~3/j6L8eXQWUIk/index.html</link>
<description>J.D. Salinger, author of "The Catcher in the Rye" and other books, has died, according to his literary agent. He was 91.&lt;div class="feedflare"&gt;
&lt;a href="http://rss.cnn.com/~ff/rss/cnn_topstories?a=j6L8eXQWUIk:Pqkyy5dEj-8:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/rss/cnn_topstories?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://rss.cnn.com/~ff/rss/cnn_topstories?a=j6L8eXQWUIk:Pqkyy5dEj-8:7Q72WNTAKBA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/rss/cnn_topstories?d=7Q72WNTAKBA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://rss.cnn.com/~ff/rss/cnn_topstories?a=j6L8eXQWUIk:Pqkyy5dEj-8:V_sGLiPBpWU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/rss/cnn_topstories?i=j6L8eXQWUIk:Pqkyy5dEj-8:V_sGLiPBpWU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://rss.cnn.com/~ff/rss/cnn_topstories?a=j6L8eXQWUIk:Pqkyy5dEj-8:qj6IDK7rITs"&gt;&lt;img src="http://feeds.feedburner.com/~ff/rss/cnn_topstories?d=qj6IDK7rITs" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://rss.cnn.com/~ff/rss/cnn_topstories?a=j6L8eXQWUIk:Pqkyy5dEj-8:gIN9vFwOqvQ"&gt;&lt;img src="http://feeds.feedburner.com/~ff/rss/cnn_topstories?i=j6L8eXQWUIk:Pqkyy5dEj-8:gIN9vFwOqvQ" border="0"&gt;&lt;/img&gt;&lt;/a&gt;

&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/rss/cnn_topstories/~4/j6L8eXQWUIk" height="1" width="1"/&gt;</description>
<pubDate>Thu, 28 Jan 2010 14:55:47 EST</pubDate>
<feedburner:origLink>http://www.cnn.com/2010/SHOWBIZ/books/01/28/salinger.obit/index.html?eref=rss_topstories</feedburner:origLink></item>

Just off a glance, it looks like you are wanting to pull out everything between the <description> desired text/string </description>

I am about to leave, but perhaps I can get back to this post tomorrow, for the mean time (im not sure how helpful this will be to you) but check out the thread I created when I was parsing some html:

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

KirkPatrick 28 Junior Poster

I didn't check out the files you have attached, but my assumption is that you need to set the size of the fan.

Personally I would just give your panel a gridbaglayout and set the weight x and weight y to your preference.

KirkPatrick 28 Junior Poster

In your post it says you need to use valueOf, however, if you aren't absolutely stuck on using that, you could probably use parseBoolean.

Once you get whether it is true or false you could take that boolean and use parseBoolean on it and then use that string to print out the sentence you need.

For example:

Boolean a; //your boolean
String result; //the string you want to represent the booleans value
a = Boolean.parseBoolean(result); //parsing from boolean to string
System.out.println("Your sentence here, plus the string's value is: " + result); //your output

Again, I'm not sure how useful this will be to you since it looks like you might have a requirement of using valueOf

KirkPatrick 28 Junior Poster

Initialize allData or allDccs (I guess there is some sort of mix-up here) in the while loop and you should be good to go without having to clear the list.

Anyways, to clarify up the matter, there is only one list in your case which is pointed to or referred by two different references. So when you say you clear one of those lists, you are actually using one of those references to clear the only list you have and hence it is giving you issues.

My apologies, I was changing the ArrayList from allDccs to allData right before I posted it which is why there was a mix up.

You are correct, initializing the ArrayList in the while loop was what I needed to do. I guess I got caught up thinking I would have to clear the array no matter what that I didn't even think that it would create a new ArrayList each time that it looped.

Thank you for the help bud, much appreciated.

KirkPatrick 28 Junior Poster

A good place to start would be in the book. Do you have any code started? If so, why not post it?

No one here will do the work for you. Show some effort and then the great members here might put forth some effort to help you. Until then, you probably won't find anyone to take your java course for you....

KirkPatrick 28 Junior Poster

I have created a function that is supposed to go through a text file (csv) and read the information in it and then add it do a dataobject (which just holds the info in textfields and a combobox) which when filled adds itself to the jpanel. The issue I am having is when it adds to the jpanel I want to add the dataobject to an arraylist (for future saving)

The ArrayList is giving me issues on what it is saving/adding. I have to clear the arraylist so that I don't end up with duplicate information, but when I clear the arraylist, it clears that arraylist in my database object. I believe I'm just over thinking the issue at hand and figured I would post it here to see if someone can pick up on what I'm missing.

public void ReadFile() {	

        String one, two, three, four, five, six, data1, data2, data3, data4, data5, data6, data7, data8, data9, data10;
        ArrayList allData = new ArrayList(); 
        ArrayList<DataObject> list = new ArrayList<DataObject>();

        try {
            com.csvreader.CsvReader reader = new CsvReader(CsvPath);
            reader.readHeaders();
            while(reader.readRecord()) {

                //get the data from file
                one = reader.get("Info One");
                two = reader.get("Info Two");
                three = reader.get("Info Three");
                four = reader.get("Info Four");
                five = reader.get("Info Five");
                six = reader.get("Info Six");
                data1 = reader.get("Data#1");
                data2 = reader.get("Data#2");
                data3 = reader.get("Data#3");
                data4 = reader.get("Data#4");
                data5 = reader.get("Data#5");
                data6 = reader.get("Data#6");
                data7 = reader.get("Data#7");
                data8 = reader.get("Data#8");
                data9 = reader.get("Data#9");
                data10 = reader.get("Data#10");

                //add data to array
                allData.add(data1);
                allData.add(data2);
                allData.add(data3);
                allData.add(data4);
                allData.add(data5);
                allData.add(data6); …
KirkPatrick 28 Junior Poster

So that would probably be free design, have you thought about trying a different layout? I prefer gridbaglayout because it allows you to set what you want by weight which is very helpful for keeping things in place.

KirkPatrick 28 Junior Poster

What layout are you using?

KirkPatrick 28 Junior Poster

Well lets think about it logically, what are you wanting to do. Lets set it in steps:

Read text file
Find the word "next"
Pull out the ints
Sum the numbers

So the first thing you'll want to look into is how you are wanting to read the file. Some suggestions are Scanner or BufferedReader

KirkPatrick 28 Junior Poster

Set the frame to a set size (probably want to set both the minimum and maximum size just to be safe, although the maximum is the one you are looking for specifically)