JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

SwingWorker makes your life easier by linking the process to the GUI update in one place then doing all the complex thread-related stuff for you. But that also means it's a fair criticism to say that this one place violates the separation of GUI and model. That makes me uneasy too, but I guess that's a personal preference.

In my code I prefer to use Observer so there is no knowledge of the GUI in the model itself. I'm a bit of a purist like that. Here is some relevant reading (!)
http://www.vogella.com/articles/DesignPatternObserver/article.html

In its very simplest form you add something like this to your process class

private ChangeListener listener = null;

public void addChangeListener(ChangeListener listener) {
   // just supports one listener to keep this really simple
   this.listener = listener;
}

void notifyChangeListener() {
   // call this whenever data is changed
   if (listener != null) 
      listener.stateChanged(new ChangeEvent(this));
   }
}

Then in the GUI somewhere you implement the ChangeListener interface (ie the public stateChanged method) and add the GUI instance to the process instance by calling its addChangeListener(this); Now whenever something interesting happens in the process you call notifyChangeListener, and the GUI's stateChanged method can update the GUI.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Here's what your code is doing at the moment...

iterator1 = ...
iterator2 = ....
while (iterator1.hasNext()) {
    ...
    while (iterator2.hasNext()) {
        ...
    } 
    // after the first pass you have now used up all the elements in iterator2
    // next time round the outer loop iterator2 will still be all used up, so
    // the inner loop will never be excuted again
}

... and here's what it should be doing...

iterator1 = ...
while (iterator1.hasNext()) {
    ...
    iterator2 = ....
    // every time you go round the outer loop you need to start a 
    // new iterator for the inner loop    
    while (iterator2.hasNext()) {
        ...
    } 
}
jalpesh_007 commented: really useful... +1
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Obviously you can pass a reference to the text area into the processing code and thus update it directly, but that would totally undermine your correctly-engineered architecture.
Or you could use the "observer" pattern and enhance your processor code to allow you to add a ChangeListener to it. Then you could update any/all listeners while processing without needing to know anything about the listeners. This is exactly the approach used throughout Swing, and is definitely "good" architecture.
Or you could use the SwingWorker class which was designed for exactly this purpose. It may take a few reads of the API doc to fully understand which methods execute on which thread, and how exactly they are related. but once you got that it's a really clean solution.
http://docs.oracle.com/javase/tutorial/uiswing/concurrency/worker.html
http://docs.oracle.com/javase/7/docs/api/javax/swing/SwingWorker.html

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

I dont understand, How am I not throwing an exception?

eg

if (! ans.equals("y") || ans.equals("n")) throw new InputMismatchException("must be y or n");
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

.Throw an error if the input number is less than zero.

You missed this part out. The catch is OK, but you don't throw the exception when the input is wrong.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Would this solution make it possible for the server to await some sort of input from both playing parties before sending out new information?

Yes, no problem. Once you have established the socket connections you open a two-way link between each client and the server so the clients can send to to server, and the server can send info to any of the clients whenever it likes

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

You can use any thread except the main Swing thread. SwingWorker is just a convenience class that helps organise and interact with a background thread, but yoyu don't ahve to use it.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

You could pass the (reference to the) ArrayList to the constructors of the various dependent classes so they all have access to it when their instances are created.

Giving them direct access to the list (via passing refs or sharing a global) can be dangerous - anyone can make any change to the list at any time, regardless of any side effects that it may have in other classes. If that's a problem you should wrap the list in a class and provide public methods for everyone else to use. That way you central control over changes etc.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Client/server coms via Java internet Sockets really isn't hard - here's a good short tutorial to start with.

A server for synch and gamestate etc is a perfectly reasonable way to go. SQL would be another area of complexity to master, so maybe better left for version 2?

Java language is pretty ordinary stuff in 2012, its the API (class library) that's really huge and takes a long time to get into. Just take it one step at a time, ie don't try to start with comms, GUI,state storage etc all at the same time.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Line 2 syntax is a bit garbled. This is the easy way to do it:
1. Create a DefaultListModel
2. Create the JList using that model
3. Add stuff to the model
4. Clear/add to the model as required

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

The ArrayIndexOutOfBoundsException meesage includes the line number where it happened, and the index value. Both these are critical info for finding the bug.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster
  1. All that crud in main down to line 24 is just setting your L&F. Yes - its boilerplate and you can move that to your "real" main method so it just gets executed once at startup. Lines 26-31 go wherever/whenever you are ready to open the main form.
  2. Java runs all its Swing-related stuff in its own thread - the "swing thread" or "event dispatch thread" or "EDT" (google those terms) via a single event queue. This includes all the screen painting, updating Swing comnponents, and calling your listeners for events such as mouse clicks. That way swing does not need to be thread-safe, which makes it simpler and faster.
    When your code needs to do something with Swing it should also use that same thread, which is what invokeLater asks Swing to do.
    Its a big topic, but you'll find the info you need starting in the Oracle Java tutorials. http://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

I would keep the main method in the project class and ignore/discard the one in the JFrame class.
My reason is that starting a program, in general, is more than just opening the main window. In real life you may need to create a database connection, start a server instance, get user/project preferences, open some files, load some shared resources, initialise a data model... all kinds of stuff that definitely does not belong in a JFrame. So in your project main you would call all that initialisation stuff, and only then create the new instance of the JFrame.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

The trick is to get the list box's ListModel (the ListModel maintains all the data that the list displays). That will give you an instance of DefaultListModel which has methods to clear the model, add elements to it etc.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

The equals method is defined in the Object class, so in the API docs you will find it listed in the "inherited methods" section. That version of equals tests for the the objects being exactly the same object (at the same memory address), so that's what you get if a class does not override it like String does.
In your test code you create two StringBuffers. They have similar data but they are two distinct different objects. StringBuffer does not override equals, so it's inherited from Object, and returns false in this case.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

String sql = ("selectfrom class where Time =? and Stage = ? and Teacher = ? ");
String sql = ("select
from class where Stage = ? and Teacher = ? and Time =? ");
All you changed was the order - which has no significance in SQL - so why bother?

The NPE is hardly surprising...
Line 4: java.sql.PreparedStatement st = null;
Lines 5-12: no assignments to st
Line 13: st.setString(1,time);
... but what is surprising is that earlier you said you had no exceptions.

You seem to be thrashing around here, posting contradictory (or at least confusing) info, and not doing any basic debugging with print statements. So that people can help, I suggest you 1. Fix the NPE then 2. add some debug prints the 3. post the latest version of the code along with the exact output it produces (from print statements or printStackTrace). Of course, you are free to accept as little or as much of this advice as you want.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Don'tknown what "it" you mean, but I have to go out for a while now, so see you later.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

If you put in the print statements I suggested then you would know what the values were that were taken from the GUI and passed to the method, and you would know that your select was returning zero rows, and you would know why.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

You really put in an e.printStackTrace(); then took it out again? That's novel.
And you put in the print statements but nothing was printed out? In that case your method wasn't being called so the problem lies elsewhere.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster
  1. Never, that's NEVER, have an empty catch block when you are devoping code (lines 27-30). How will you know if Java has detected an error? Always start with an e.printStackTrace(); in every catch block.
  2. If you do that, but there are no exceptions thrown, then add print statements to confirm key info like: the values of the parameters passed to the method and the size of the result set. But first, e.printStackTrace();
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Please don't forget to mark your threads as "solved" if/when you get the answer you need.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

It's integer arithmetic, normal maths priority, so
cor/10 = 0 (would be 0.3333, but this is integer math)
0*50 = 0
0+50 = 50

To fix it, change the order of your expression so the * is done before the /, ie
cor*50 = 150
150/10 = 15
15+50 = 65

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Yes, that's the right syntax. I don't know why thats unreachable. Please post the exact version of the code that gives that error, and the exact complete error message.
Java error messages always tell you the exact line where the error was found.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

It's a method in the same class as where you're calling it from, so you can just call it by its name; you don't need to put anything before the method name. Also you will need to pass it a String[] as a paremeter in the () after the method name.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster
  1. You have defined a print method with one parameter (String[]), but when you try to call it you don't pass any parameter. In other words: student.print() is looking for a print method with no parameters, and you have not defined any syuch method.
  2. student is an array of Strings, so student.print() is looking for a method print() that is defined in the String[] class.

The definition is OK, so it's the call you need to fix. Once you have dome that you will get a "Non-static method cannot be referenced from a static context" error - try to fix it yourself before coming back here for more help.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Do you have an error message (eg something about static context?). If so please post the exact complete message (copy/paste, don't summarise it)

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Sorry stultuske, but I found your reply very confusing. Once you create an instance of some concrete class that instance can never change its type. A SampleB can be added to a Vector<SampleA> because SampleB is a subclass of SampleA. But nothing is "stripped from the instance", and a SampleB can never be "transformed" into a SampleA. That instance is still a SampleB with all the extra info that a SampleB has.

What's happening here is that the compiler doesn't know at compile time whether any particular element in the Vector is going to be a SampleA, B, or C. All the compiler knows is that all the elements of v are SampleA.
You then try to assign a value from v to a variable of type SampleC. Not all SampleA's are SampleC's, so the types are incompatible.

stultuske commented: nyes, should 've chosen my words much better. probably the reason I never became a teacher :) +14
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

(to clarify Majestic's post:
== works exactly as the language definition says it should, including for Strings. It tests for two references being equal, ie referring to exacty the same object. However, it doesn't do what beginners sometimes think it does, ie test for two Strings containing the same sequence of characters - that needs the equals method)

Because Strings are immutable the compiler is able to optimise String literals by sharing them.
eg1,2: It creates a "hello" string for the first statement, then re-uses the same string for the second. The == test (tests for being the same object) is true.
eg3,4: Using new String explicitly overrides the compiler's optimisation and forces it to create new String object. Now there are two different String objects, so == is false. (But x.equals(y) is true becuase they both contain the same sequence of characters)

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Because the if/else/print"no" is inside the while loop it will be executed once for each line in the file. Your logic should check for the password being in the file, then display the frame or the error afterwards. Something like this (pseudo-code)

boolean passwordFound = false
read each line of the file...
   if password matches set passwordFound = true
after end of file...
   if (passwordFound) show frame
   else show error message
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

... and what exactly is the compiler error!

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

When you created the instances of Node that currentNode refers to, what did you have in the <>
How is curentNode defined?

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

That's just how postfix works. O
n line 4 the value of x-- (10) is passed to the met method, then the value of x is decremented. In the method met, the value of the expression x-- (also 10) is evaluated. The parameter x is them decremented, but this is irrelevant because it immedtately goes out of scope. The evaluated value (10) is then returned. Finally back on line 4 that value is assigned to x.

ps rahul - if you are satisfied with an answer / answers to ypur questons please mark the thread "solved" so others fgind it useful as well.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

It can be very confusing to talk about var's and object's types, so I'm going to stick to the proper Java terminology. st is a reference variable that can only refer to objects of type Sample1 or any subclass of Sample1.
(Sample2) st creates a reference that can only refer to objects of type Sample2 (or any subclass of Sample2).
At compile time the compiler can't determine whether that will be valid or not, so it's checked at runtime. At runtime it discovers that st is referring to a Sample1, so that is not a valid value for a (Sample2) st reference. Hence the exception.

Without line 14 it discovers that st refers to a Sample2, so the cast is OK.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

st is a copy of s1, which is a ref to a Sample1. You then try to cast that so Sample2, which is invalid.
The relevant rule is that you can cast a subclass to it superclass, but not vice-versa.
This is because every Sample2 is, by definition a Sample1, but not every Sample1 is a Sample2 (all Cats are Animals, but not all Animals are CAts).

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

I'm very confused.
Your first post in this thread said

NOW I am asking to you how can I use and modify MyClass according to sending/receiving sound record, NOT FROM A FILE.

now you say

Problem is sending file ...

can you see why that is confusing?

If the problem is file size, then the first code I showed in one of your earlier threads breaks the file into small chunks for sending. Did you read that code?

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

OK. Sorry, but I have no experience of MediaPlayer for Android, so I cannot help much. Maybe someone else knows more about it? Good luck anyway.
J

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Sorry about the colloquial English - I will try to keep it simpler.
Are you using JMF?
If so, maybe you can treat the voice input as a PushBufferDataSource. That will call your listener and pass it buffers of sound that you can send to the receiver via the Object output/input streams. At the receiver you can process these buffers in the usual way.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

OK, you have code to show a letter grade. What exactly is wrong with the results it gives you?
Maybe you are getting multiple letter grades? Eg if the grade is 80 then it will pass the if tests on lines 43, 46, 49, 52 and 55. Have a look at "else if" rather than "if" and see how that can help you stop processing subsequent if tests once you have passed one of them.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

So your sound is in a byte array? In that case you can simply write that to the socket via an ObjectOutputStream. At the receiver you just read it via an ObjectInputStream and now the receiver has a copy of the sender's array. You already have code to do that, because your file sending code first creates a byte array from the input file, then sends it. Similarly at the receiving end you read the data into a byte array before writing it to the output file. The code you need is just a subset of the code you already have.
The interesting part is how to get the sound into a byte array in the first place, and how to play a sound that's in a byte array. That depends on what software you are using to recoed and play, and exactly how you are using that software.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Java programmers are very pedantic - they have to be. You said
"I am wondering what the 'this' in the following code refers to ... I believe that it refers to the run method".
So technically that's false, even if you did have the right idea.
Anyway, mark this thread solved?

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

In Java "this" is always the current object - the one whose context the current method is executing in. The Thread constructor takes an instance of Runnable as its parameter, so "this" must be an object whose class implements the Runnable interface (which consists of a single run method). When the thread is started it will call the run method for the "this" object.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Java is not the same as JavaScript. You have posted in the wrong forum.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Yes please. There's a "mark this thread solved" link at the bottom of the page.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

I agree. The wait would be less code, but the button is far better user interface - it puts the user in charge.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Sounds like a job for the javax.swing.Timer
http://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Integer values won't fit in a byte. Perhaps you could show a small example of what Integer values you expect, and how they should look after being converted?

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Maybe you have a class of your own called Date that is in the same directory as this code?

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

You do realise that this is the Java forum? And that Java already comes with APIs that include parsing/converting numbers from/to any arbitrary base?

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

getBytes will extract the text bytes from the string - it doesn't know or care about hex. It will give you {'1', '0', 'B' ...
Then you convert each of those and you get 32 integer values each in the range 0-15.
To decode that as 16 integer values each in the range 0-255 you need to use substring to split the string into 16 strings each 2 chars long, then parse those.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

You have that error message because you out an executable statement that's not in a method. Executable statements need to be in a method or constructor. That could be main, or any other method that gets called directly or indirectly from main (including constructors).

(Ps: for the experts out there, I'm deliberately ignoring static and instance initialisers as being too advanced to be relevant)