JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

There's nothing at all wrong with that - look at possibly the most used Interface in Swing - ActionListener
(Which is also the pattern to follow - have the Model implement a proper Listener interface such as:

public interface ModelChangeListener {
   public ... modelChanged(); // or maybe more for different kinds of changes
}

// in the model:
public void addChangeListener(ModelChangeListener mcl) { etc

// in the controller
public ... modelChanged() { etc
...
model.addChangeListener(this);

If you don't want a separate file for a one-method interface you can always define it as public in the main Model class and refer to it via Model.ModelChangeListener

mKorbel commented: http://stackoverflow.com/questions/6117908 +8
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Reflection is useful when you have to make calls dynamically at runtime to classes/methods that are unavailable at compile time, and for implementing annotations etc, but they are not normally used for "ordinary" code. A major reason is that, unlike normal calls, they cannot be checked at compile time thus requiring extra effort in testing, debugging, and error handling at run time.
Interfaces are self-documenting, formally checkable, and the way to go for approx 100% of MVC apps.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

It MAY be false. The compiler tries to re-use Objects where possible, so depending on the exact way it's coded two different Integers (with the same value) MAY be optimised to the same Object and therefore be ==. The moral is never to use == on any kind of Object unless you are certain that that's what you mean.

ps The default range of values for which Java uses a pre-cached Integer is -128 to +127, but you can use the java.lang.Integer.IntegerCache.high property to increase the size of this cache.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

This http://www.jvoegele.com/software/langcomp.html is an excellent article on the subject. It's a bit out of date - eg is says Java doesn't have generic classes, but these were added to Java in version 5, (2004) - but the definitions and analysis are spot-on.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

i am so sorry i could't understand all that, there is some words that does't in the dictionary, and the meaning is not reach to me as u want (i think)
any way thank u very much for ur contribution
regards

Don't worry - m. was just saying it in a humorous/funny way. His point was:
if you have a boolean variable or expression b then b==true is not good code. It's the same as just b, but longer. Here's the truth table:

b         b==true
-         --------
true      true
false     false
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

1. readObject can throw Exceptions (see the JavaDoc for details) so you have to use try/catch to handle them.
2. In Java 1.5 collections like Vector were enhanced to allow specification of what kind of Objects they contain (previously they just contained Objects, which had to be cast at runtime to (hopefully) the appropriate class. Since 1.5 you can say things like
Vector<String> v = new Vector<String>(); // this vector always and only holds Strings
So now Vectors without such a specification are called "raw types", and you are strongly recommended to update them to the improved version. If the vector really does hold absolutely any kind of Object, you can use Vector<Object>.
Look up "Java generics" for more details.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

I mean
if (spoof && th<T1) then all your if tests are false and you will do nothing
similarly,
if (!spoof && !(th>=T1 || th<T2)) then all your if tests are false and you will do nothing

Maybe your 3rd line, where nothing was printed, is because one or the other of these two things happened. You can check that by looking at spoof, th, T1 and T2 for that line.
If that is the problem, then you could add these cases to your set of if tests, or you could have a final else clause that prints "none of the above", so you know what's happening.

If I'm using English words you don't know, please ask. I'm English but I live in France, so I know how hard it can be to work in a foreign language.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

General strategy:
Don't try to use paintComponent for viruses or ships, they do not extend anything with that method. Just have a public paintMe(Graphics g) method for each.
Have the game panel with its overridden paintComponent method, and within that method call paintMe(g) for all the viruses and ships so they paint themselves on the game panel.
Rather than dodgy pause methods, use a javax.swing.Timer timer to call your move/repaint method at regular intervals. This is designed to work properly with Swing's approach to threads.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

You normally only need an ImageObserver when you are loading an image asynchronously and need to know when it's finished loading (eg in a web page). Once the Image is loaded you just need the Image itself (or a suitable public method in the class that "owns" the Image).

ps It's OK to pass null as the ImageObserver to getWidth/Height if you are confident the Image has finished loading.
int width = image.getWidth(null);


pps: Crazy Dieter - did you notice this zombie thread is a year and a half old when you tried to resurrect it? (And stupid me for not checking)

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

OK. That tells you the problem is nothing to do with your Scanner.
It's always important to read carefully what the Exception messages say. They usually tell you exactly what the problem is and where. In this case:
It's a NumberFormatException. You can look that up in the API JavaDoc to find exactly what it means. In this case, tried to parse a String as an integer but the String did not have the right format for a number because it was empty ("").
It happened in the Integer.parseInt method which you called at line 14 of your main method of IP2HC_Inspect.
(No, I'm not psychic - all that is in the error message you posted.)

That should be enough info for you to be able to find your problem.

ps: Typed that before I saw your later post without the Exception. So now you enter two lines (and a blank line I presume?) and your program terminates without error. Not much I can do about that.
Put lots of print statements into your code so you can see which blocks of code are being executed and what the values of your variables are. If you do enough of these you will find your problem.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Create a small class to handle the click. Have a constructor for that class that takes an int as parameter and saves its value. Crate a new instance for each JLabel, with the JLabel's index as parameter. Now when you handle the event you have the index of the JLabel it relates to.
ps I also like Norm's client property approach
pps Forum protocol is that, if you cross-post in different sites, you should say so.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster
GameBoard b = new GameBoard ();
...
frame.getContentPane().add(b);

Apart from the anachronism of the getContentPane() - not needed for years now - the driver adds an instance of GameBoard to a JFrame. Check out JFrame's (or content pane's) add method - what kind of objects can you pass as the parameter to that method? To make this code legal your GameBoard class will have to be a subclass of one of those kinds of Objects.

This is a quite common pattern - create your custom GUI thing as a subclass of (say) JPanel so an application can just add it to a window that will contain other buttons, menus etc.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

I still think it is my comparison making going against itself but I don't know how to fix that.

Yes, that's the problem.
You loop thru all the balls taking one at a time and comparing it with... itself. (Rectangles r and p are always identical.)
You need to compare two different balls, which should instinctively suggest that you need two loops.
Remember also that if you've compared 1 with 2, the there's no need to compare 2 with 1.
So the comparisons you need to do look like this:
1 vs 2, 1 vs 3, 1 vs 4 ... 1 vs n
2 vs 3, 2 vs 4 ... 2 vs n
...
n-1 vs n
I'll leave you to think about how to code those loops.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

What are the symptoms you are getting? - you don't actually describe the problem anywhere.
Does your animation loop actually call the method to test for collisions after calling move?

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

RMI involves a big learning curve and quite a lot of code. IMHO it's not appropriate unless you have identified a need that requires that kind of power, flexibility, and client/server integration. If you just have a small number of fixed messages ("I'm employee 1234, can I come in please?" - "yes") then Sockets are all you need. You'll find a bazillion (+/- 20%) code samples on the web showing how to listen on a server port, establish a connection, and send/receive messages via input/output streams across the connection. The code's not much longer than the description.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Wow. This has turned into a (very interesting) debate about how to associate arbitrary blocks of code with arbitrary names, and that is a real Java problem, but it's not what DeanGrobler asked:

whatMethod() accepts a String and then decides what method to execute based on the received String. Say the String that was sent to whatMethod() was "method2", then whatMethod() will execute method2()... How would you go about doing this?

I guess my original post may have been too cryptic, so here's a better explanantion:

Given the name of a (no args) method in String name, the following line of code executes the method:

getClass().getDeclaredMethod(name).invoke(this);

Realistically, just how simple do you want this to be?

With error handling, and packaged as a method it's still not hard:

void whatMethod(String name) {
      try {
         getClass().getDeclaredMethod(name).invoke(this);
      } catch (Exception e) {
         System.out.println(e);
      }
   }

Finally, in 17 easy lines, here's a complete runnable demo of it in action:

public class Demo {

   void whatMethod(String name) {
      try {
         getClass().getDeclaredMethod(name).invoke(this);
      } catch (Exception e) {
         System.out.println(e);
      }
   }

   void method1() {  System.out.println("Method 1 called"); }

   public static void main(String[] args) {
      new Demo().whatMethod("method1"); // should call method1()
      new Demo().whatMethod("method2"); // should error - no such method
   }
}
peter_budo commented: Nice sample James +16
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

You can use Reflection to execute a method given its name in a String. Something along the lines of:

import java.lang.reflect.Method;
   public void invokeByName(String name) throws Exception {
      Method method = this.getClass().getDeclaredMethod(name);
      // throws NoSuchMethodException if method is not found
      method.invoke(this);
      // may throw IllegalAccessException,IllegalArgumentException, InvocationTargetException
   }
Dean_Grobler commented: Exactly what I was looking for, thank you so much! +3
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Another thought
When you have finished communicating with a client you close the ServerSocket (line 76) when you should be closing the connection Socket, so the accept method throws a socket closed exception and all subsequent attempts to use the connection fail.
If I'm right you should be able to make one successful client connection before it all goes Pete Tong.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

The only thing that looks odd to me is Client line 21 out.flush(); where you flush before the first write. That's probably harmless, but definitely redundant, so maybe try taking it out?

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

You need to return a variable that holds an array of Rectanges. Rectangle[] isn't a variable. Think now - what is the variable that holds your array of Rectangles?

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

If the things are in any kind of Collection you can use addAll(Collection c),
If it''s an array you can use Arrays.toList(...) to convert the array to a List that you can pass to addAll

but is there a way to add things into arraylist iteratively one by one?

That is exactly what your code is doing!

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Its the same as int except that it holds very much larger numbers
For int, from -2147483648 to 2147483647, inclusive
For long, from -9223372036854775808 to 9223372036854775807, inclusive
You use it whenever you want an integer value that may be bigger than the largest int

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Java variables come in 2 flavours, primitives (eg int, char, byte, float, boolean - all lower case names) and reference variables (which you can think of as pointers).
All variables of array or Object types are reference variables. So, in your code message_one and message_two are reference variables of type String, or string pointers. The memory for those pointers is part of sscanner's memory. Initially they are both null (refer to nothing).
"Hello!" and "World!" are two new instances of the String class whose memory is allocated in the heap. Your two variables are then set to refer to these two instances. ie
message_one -> "Hello!"
message_two -> "World!"

You then execute
message_two = message_one;
which copies the value (the reference or pointer value) of message_one to message_two. After which
message_one -> "Hello!"
message_two -> "Hello!"

There are now no remaining references to the "World!" object, so it will be garbage collected and its memory released.
Finally you execute
message_one = scan.nextLine();
scan.nextLine() creates a new String object containing the user input, and message_one's value (the reference or pointer value) is set to refer to that new String, so you now have
message_one -> "This is a test sentence."
message_two -> "Hello!"

\007 commented: Thanks! +2
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

There's a standard way to do this:
1. Change the WebCrawler constructor to take an instance of CrawlAnalyseGUI as a parameter - so line 15 will read
final WebCrawler crawler = new WebCrawler(this);
Now the webcrawler has a reference to the GUI.
2. Add a public method to CrawlAnalyseGUI that can be used to update the GUI with progress from the crawler - mabe something like
public void updateProgress(int toDo, int done) {
// update JLabels etc
}

3. In the WebCrawler, whenever there is progress to report, call updateProgress on the GUI instance (as passed to its constructor).
4. Sit back, watch it work perfectly, feel smug.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Good fun! You seem to be developing a wide range of web-related skills. I see a great future ahead for you.....

NewOrder commented: thanks for the java help +3
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Use a JDialog for the subframe - you can control its modality to block all input to other windows in your app while its open (and other variants)

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

From the EditorPane you can get its EditorKit, and from that you can get the Document itself.
You can add a DocumentListener to the Document to be notified of all changes the user makes. Send those via the Socket connection. At the other end you can insert (or remove) the changes in the other Document.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

I've never tried this, but the nodes in JTree are rendered by default using JLabels.
You can put multi-line text in a JLabel by using simple HTML, so maybe you can use HTML to get multi-line nodes? Try a node with text like this:
<HTML>line 1a<BR>line1b<?HTML>
you never know...

Just tried it - it works.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

On the other hand
If there's no need for any interaction between your app and the extension you can just use ProcessBuilder to execute any other runnable jar in its own VM

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Hmmmm. It looks to me like you are on mission impossible here. IMHO it needs to be re-implemented. Sorry, I have no more ideas.

If I'm monitoring DaniWeb for interesting new posts I use a neat Firefox addon called ReloadEvery http://reloadevery.mozdev.org/ and set it to refresh the page every 5 mins or so. Works a treat for me.

Majestics commented: Thanx..... +3
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Nice to know that thre are two of us on the planet who are not watching the royal wedding

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Despite appearances that ian't a file. The .class operator is used with a named class to get the Class Object representing that class. So
DefaultWeightedEdge.class
returns an instance of class Class representing the DefaultWeightedEdge class.

It's passed as a parameter to a method to tell the method what kind (class) of Object you want to be created in that method. It's needed as a work-around for a limitation in Java 1,5 types that means you cannot do this:

void myMethod(T param) {
  new <T>();

but you can do this

void myMethod(Class paramClass) {
  paramclass.newInstance();

ps: more info if you're interested
http://stackoverflow.com/questions/75175/create-instance-of-generic-type-in-java

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

A couple of observations:
1. You have 3 consecutive try/catch structures. If the first one fails you log the error - good - but then go on to try to access the file anyway.
It would be better to put all that IO code in a single try/catch so that if any one step fails it doesn't attempt the rest. Alternatively, return; after logging an error, since there's no point continuing with the method.
2. Now how to access these values from other classes?
2a. Write public getXXX methods for each of them
2b. Make the variables public final so anyone can use them, but not change them. This requires that they all get set in the class's constructor(s).
2c. Make the Properties object available to other classes, since the syntax to retrieve a property from it is so easy. Then you don't need to publish a dozen values separately, and if/when new properties are added the code doesn't change.
2c(1) ... by writing a public getProperties method
2c(2) ... by making configProp public final (although this will allow users to change properties directly.
2d. Write a single public getProperty(String key) method that just delegates to the Properies object, and get rid of the dozen separate variables. This has all the advantages of 2c, but proptects the values from being changed.

I personally would probably go for 2d..

Regardless of which of those routes you take you also have …

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

It tests curIndex to see if it's valid as an index for appObj.array.
If it's not valid then the method sets the display to blank, after which it can't do any more so it returns directly to the caller.
If it's valid then it goers on to set the display based on the data.

In this particular case you could achieve the same result with an else:

if (curIndex<0 || curIndex>=appObj.array.size()) {
  display.setText("");
} else {
  display.setText( appObj.array.get(curIndex).toString();
}

but if there was a lot more processing to do then the first version is cleaner.

This is a simple example of a common pattern:

test to see if parameters are OK
if not - just return; // cannot continue
continue doing all the processing for this method with valid values.

jon.kiparsky commented: Great minds think alike... and so do ours... +11
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

we can add "no indentation" to that as well. Stephen: have you upgraded your crystal ball to 1.6u22 yet? I hear that there are problems with temporal leakage in the future vision support.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

im so dumb

If you are, then so is everyone else who has ever posted or replied in this forum!
We've all done something like that, more than once.
You can often find that kind of "blind spot" error by explaining your code line-by-line to someone else - as soon as you have to read each line of code out loud you often realise that what you wrote wasn't exactly what you intended...

ps Thanks for letting us know how it turned out - it's surprising how often people disappear as soon as they get an answer and just leave the topic open.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Line 15 - yes, when you declare a new array of Sports the array is empty - it just contains slots that you can put Sports in. If you try to access an empty slot you get a null pointer Exception. Your loop at line 15 puts a new Sport object into each of those slots, so now they all have something valid in them.

Line 70 - you set i back to zero every time you go thru the loop, so every entry just goes into [0]

Line 16 - end the for loop, so the following code is now outside the loop and only gets executed once. The } probably needs to be about line 63.
This would have been more obvious if your indentation was correct - it currently shows how you think the code should be, not how it actually is.
If you're not currently using a tool that indents code for you, then I recommend you start now, and keep the indentation updated.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

1. If you really insist on trying to compare an int and a String then your best option is to convert the int to a String, then compare that with the key. One of the toString methods in the Integer class will do the conversion for you (I'll leave you to find out which).

sportEvent.getVenue() vs sportEvent.venue
This is almost a religious question and people can get quite heated about it. My own opinion is that exposing a classes instance variables is asking for trouble - sooner or later another method in another class on another thread will do something unexpected with one of those vars and the debugging will be horrible. Forcing people to use get/set keeps you in control.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

if (sportEvent.getYear.equals(key))
where getYear returns an int, and Key is a String
won't work because
a) an int is never equal to a String
b) ints are primitives, not classes, and have no methods. sportEvent.getYear returns an int, but then you try to call .equals(..) on that.

One possible thing to think about is a polymorphic search method with 2 variants- one taking a String as key (searching name & venue only, the other taking an int as Key, and searching only to year.

If you fix that problem I think your search will work.

As for adding - one thing is that you increment i before adding the new record, so the first record goes into array[1] and array[0] is left empty, ready to give you null pointers etc when you try to access it. And i is a really unhelpful name for that variable!

There are lots of other things that can be improved, but that should do for now.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

You have loops that look like this one:

for (i = 0; i<sportEvent.length; i ++)  {
  System.out.println(sportEvent[i].getTitle());

but there is no guarantee that the array is full of actual data, eg if you have an array of size 8, and have entered 6 records, the last two slots in the array will be empty and your attempts to retrieve data from them will fail.
Normal practice is to make the array "big enough" and have a separate variable that counts the inoputs and tells you how many elements of the array contain actual data.

Double post? Oh well.

ps: Your setX methods are all called getX - very confusing.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

If it didn't run then, yes, you're doing something wrong!
But without (a) the code and (b) an EXACT description of what does or does not happen when you try to run it (including the full stack trace from any Exceptions), there's nothing more anyone here can do...

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Google "Event Dispatch Thread" (EDT or "Swing" thread).
All GUI updates are single threaded on the EDT, as are all GUI-initiated user interactions. So your jButton2ActionPerformed executes on the EDT. While it's executing all other GUI-related activities are queued (including your progress bar re-paints).
There are a number of ways round this but they all involve moving your long-running task off the EDT onto some other thread, thus un-blocking GUI activity. Generally, the SwingWorker class (new in Java 1.6) is a very good option. The standard JavaDoc includes an example of updating a progress bar from a long-running process.

ps Using Thread sleep inside an ActionPerformed is a common beginner's mistake (as explained above) - it can only help if the process has been handed off to another thread. eg by using SwingWorker. In that case you can use sleep to artificially slow down your progess, if that's what you want.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Start by studying this section of the Java tutorials and the following few pages:
http://download.oracle.com/javase/tutorial/uiswing/painting/index.html

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Hey! Was that deliberate? Normal phrase is "heart of gold", but you wrote "hard" as in tough. difficult etc. Neat pun!
I still stand by what I said.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

READ THE DOCUMENTATION!

http://download.oracle.com/javase/tutorial/uiswing/misc/timer.html
http://download.oracle.com/javase/6/docs/api/javax/swing/Timer.html

If you can't use Google to find code samples, tutorials, and reference materials you will never be able to write programs, in any language. Getting someone else to do it for you is not an answer.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

javax.swing.Timer is what you need - documentation & samples in the usual places.

Define a timer task (a "run()" method) that you want to run repeatedly. On click of the start button start a Timer that will run that task every 3000 msec. On click of the stop button stop the timer.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Good morning S.
This is your homework for you to do. I'll help, but I won't do it for you. I've given you a stack of info to think about, so now it's your turn to put in some serious effort.
Sorry if that sounds harsh, but it's how things work around here, and it really is the best way.
J

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Yes, that, in general terms, is how its done. The instance variables may hold the info needed to do all the work in paintComponent, or they may just be a list of objects that have their own paint methods that can be called from paintComponent to delegate the work. Those 2 options pretty much cover it; experienced developers may be more likely to go for the second variant, depending on the exact requirements.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Black box testing tests the system as a whole, based on its external specification, without any particular reference to how it is built internally - it treats the system as a "black box" with unknown contents

White-box testing (better known as clear box or glass box testing) is based on a knowledge of how the system is implemented, so unlike black-box testing it can look at internal states and intermediate results, and can target specific use cases or data combinations that look challenging for the actual implementation.

eg:
BB tests for a personnel system will enter employee data and request reports and check that the reports are correct.
GlassBox testing will also look at database dumps to see if the tables have been populated correctly, and will have specific test data that hits and passes the known database limits on field sizes etc.

In theory BB is all you need - if the correct inputs lead to the correct outputs, and incorrect inputs are handled appropriately then the system is good.
However, no tests can cover every possible sequence of correct and incorrect inputs, so glass box testing is useful to target additional effort into places where problems are more likely to be found.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

We'll help you get started ... but only if you show that you're willing to put in effort as well.

How far have you got researching this yourself? What sources of info have you used?