Java Forum / General / April 2006
Java GUI Problem
DyslexicAnaboko - 10 Apr 2006 05:10 GMT I am having a problem that has really got me stuck and I think it is because I am going about it incorrectly.
Here is my problem in the most plain terms possible:
I wrote a program that has a Class "A" and for class A there is a GUI class called "A_GUI" in its own package called "GUI".
The following should occurs between the two classes:
I launch Class A, which will in turn invoke class A_GUI.
It is done in this order because class A need to load data from certain files and what not before A_GUI can be useful.
The A_GUI class has two fields to fill in, for arguments sake we will call them the: userName and passWord fields.
When A_GUI is invoked the user is prompted to input his userName and passWord. After the user puts in their information they will press login. Login in turn will send the users input back to class A for validation. Class A will validate the user and log them on to the system.
The problem I am having occurs at the creation of A_GUI. The specifics are that the screen launches successfuly, however class A continues to run after invoking class A_GUI. This is a problem because class A is trying to validate two strings that have null values. This ends up making the program stop and throws a null pointer exception for very obvious reasons.
What I want to do (correct me if I am going about this the wrong way) is somehow tell class A to WAIT until it gets a response from A_GUI, and then, and only then will it proceed to function. I think this has something to do with eventListeners, but I do not know how to make one class listen for another class.
I would greatly appreciate it if someone could help me with this because I am at total loss.
Roedy Green - 10 Apr 2006 05:20 GMT On 9 Apr 2006 21:10:46 -0700, "DyslexicAnaboko" <DyslexicAnaboko@gmail.com> wrote, quoted or indirectly quoted someone who said :
>however class A continues to >run after invoking class A_GUI A class does not run. A method in that class can run. Normally the idea is you launch your GUI then return. The GUI part continues to run when events are created by the user clicking things.Everything is running on the Swing event thread.
Perhaps if you created a miniature version of you code and posted it, it would be clearer what you are talking about.
 Signature Canadian Mind Products, Roedy Green. http://mindprod.com Java custom programming, consulting and coaching.
DyslexicAnaboko - 10 Apr 2006 16:30 GMT Okay, here is a reduced version of what I am doing:
//This is the constructor of the director class (class A) public Director() { //Loads user information into a TreeMap for the class accessMap = reg.getValidUsers() ;
//While the user is not valid the keep object of the GUI class //"LoginGUI" alive (A_GUI) //The object name is "loginScreen"
while( valid == false ) { loginScreen.setVisible( true ) ; //Launch window
//Source of my problem is here, I want the user //to be able to type something in before the //following methods try to validate anything at all.
//String userName gets the input for the //user name from the login class.
//String passWord gets the input for the //pass word from the login class.
userName = loginScreen.getUN() ; passWord = loginScreen.getPW() ;
//This method is not shown, but it validates the userName //and passWord against the list that was loaded up above //during the creation of this class (class A/ Director class).
valid = validate( userName, passWord ) ;
//println for testing purposes, is the user valid? true or false.
System.out.println( "User valid? : " + valid ) ; }
//If the user name and pass word are correct, then disable the GUI.
loginScreen.setVisible( false ) ;
//Direct this user to where ever they are determined to go //(don't worry about this) //Direct this login
director() ; }
==========================================
I really appreciate everyone's help. I will try everyone's suggestions.
Roedy Green - 10 Apr 2006 17:39 GMT On 10 Apr 2006 08:30:43 -0700, "DyslexicAnaboko" <DyslexicAnaboko@gmail.com> wrote, quoted or indirectly quoted someone who said :
>public Director() >{ > //Loads user information into a TreeMap for the class > accessMap = reg.getValidUsers() ; This is not valid code. You can't have assignment statements except inside methods or inside static or instance init blocks.
You made a peculiar comment earlier about a "class" running. I think this may be one of the keys to your problem.
 Signature Canadian Mind Products, Roedy Green. http://mindprod.com Java custom programming, consulting and coaching.
DyslexicAnaboko - 10 Apr 2006 20:48 GMT Its nice that you don't think this is valid, but it isn't a coincidence that I have written code like that before and it executes properly and easily. If that is not proper code then tell Mark Allen Weiss that he is not coding properly as well. I took data structures with this professor and he is a very well known programmer. He too makes his constructors like that and yes you can have assignment statements inside of constructors, you are wrong.
If you don't believe me then go ahead and try it before you point the finger.
Plus I don't appreciate your poking fun at me. If that wasn't your intention then I am sorry to be accusing you of such, but that is how it comes off.
Oliver Wong - 10 Apr 2006 22:26 GMT > Its nice that you don't think this is valid, but it isn't a coincidence > that I have written code like that before and it executes properly and [quoted text clipped - 3 lines] > constructors like that and yes you can have assignment statements > inside of constructors, you are wrong. When I saw your code, I thought that was a class declaration, not a constructor (and I suspect Roedy made the same mistake). He's right that you can't have arbitrary code directly inside a class, and you're right that you can have arbitrary code inside a constructor. To avoid confusion, you might want to format your code into an SSCCE so everyone knows exactly what's going on. http://mindprod.com/jgloss/sscce.html
As for Mark Allen Weiss and good coding style... well, let's just say I personally wouldn't put "while(valid = false) { loginScreen.setVisible( true ) ; /* ... */ }" inside of a constructor.
- Oliver
DyslexicAnaboko - 11 Apr 2006 01:12 GMT Yeah, don't pin that on Mr. Weiss, he would know better I suppose. All i'm saying is he does decalre varaibles and what not in a constructor. What ever I did doesn't mean he would do the same, all I was trying to say is that i've seen it done.
I will do my best to take a glance at the SSCCE, I am not familiar with it and I am very pressed for time, however I will get to it when I can.
Alex Hunsley - 11 Apr 2006 01:11 GMT > Its nice that you don't think this is valid, but it isn't a coincidence > that I have written code like that before and it executes properly and > easily. As Oliver points out in his reply, I think Roedy thought that you were posting the code for a class, and not for a constructor. I believe he thought that because of a combination of a) you didn't post the outer class definition, only a constructor, and b) the code in that constructor looked very non-constructor indeed! The code is 'valid' in that it will run, yes. However, the code is not well written, in that it is doing waaay too much inside a constructor.
> If that is not proper code then tell Mark Allen Weiss that he > is not coding properly as well. Mark Allen Weiss, your code (as posted here) is not well written. There you go. Please show him this if you feel like it, and invite him to join the discussion! Just out of interest, do you always assume that Professors know the best, at all times? It's not always the case. No en-masse slight intended to those in academia, but: I've seen staff-written code given to students on computer science degrees (at the most venerable institutions) that was questionable in its practices. Lecturers and professors are not perfect, please disabuse yourself of the notion that they necessarily create good code! (Contrariwise, I'm sure some of them are very good...)
As to why that code is not well written - here is why: Classes in OO represent nouns (or 'things'), and are named as such. You can still have a class as a noun while also suggesting what it does (i.e. provide a verb). An example is the code you posted, which was for a class called Director: a director being a thing (noun) that directs. As another example, a class that handles FTP connections might be called FTPAgent, or FTPConnectionManager, or similar. Examples of poorly named classes might be Direct or Connect. These are verbs.
(Bear with me a little longer...)
Now, because classes should be nouns (things), and constructors are for constructing these things, it doesn't make a lot of sense for a constructor to actually *do* many things. A constructor should construct something - an object instance - that's the semantics of construct. The *actions* (think verbs) an object performs should generally be presented as methods (and that includes populating a non-trivial GUI component or showing a GUI component).
You may think this is all wishy washy hair splitting, but there are good reasons to follow these guidelines. People sometimes get burnt trying to do too much in constructors: to see why, try the following:
Q: What does the code below output to the screen? (You're not allowed to run it. Just answer by reading the code.)
(I'd like you to ask your professor too. And if he knows the correct answer, why does he think it's a great idea to encourage people to shove reams of code into a constructor?)
class A {
public A() { setUpSomeThings(); }
protected void setUpSomeThings() { // some setup code in here }
}
public class B extends A { private int memberVariable = 0;
public B() { super();
System.out.println("memberVariable = " + memberVariable); }
protected void setUpSomeThings() { memberVariable = 7; }
public static void main(String[] args) { B bInstance = new B(); }
}
Bonus question: What is the output if we change the line:
private int memberVariable = 0;
to:
private int memberVariable;
?
> I took data structures with this > professor and he is a very well known programmer. ... with really bad habits vis a vis Java constructors, apparently. I am not impressed with this style.
I've just looked up your Professors site. Here's a sample of his code:
private static int max3( int a, int b, int c ) { return a > b ? a > c ? a : c : b > c ? b : c; }
Can you see anything wrong with this style? Put simply, it's a confusing mess. Maybe putting this into one line, without even any brackets, gave him warm fuzzies and made him feel clever. Great for him, crap for anyone else who comes along (including him at a later date, possibly). Just the act of adding some brackets makes that code vastly more readable:
return a > b ? (a > c ? a : c) : ( b > c ? b : c);
And arguably you could even have: if (a > b) { return a > c ? a : c; } return b > c ? b : c;
Some people would cry "but it's obvious what the method does from the name, it gives you the maximum of three params!" - no, it's obvious from the name what method *should* (and may, or may not) do.
(Observation: your Prof seems to be used to writing and handing out code for others, but not so used to being on the receiving end of code written by others.)
> Plus I don't appreciate your poking fun at me. If that wasn't your > intention then I am sorry to be accusing you of such, but that is how > it comes off. I'm very sure that he didn't mean it as poking fun. He just got the wrong end of the stick about the meaning of the code you posted (i.e. thinking that it was a class, not a constructor).
As a final note, there are some guidelines for a misery-free existence regarding constructors:
1. Do as little as possible in constructors. If you need lots of logic concerning object creation, favour factory methods or similar.
2. Ideally, don't call non-final and non-private methods from constructors of non-final classes.
3. If you break rule 2, document this, and don't access any object state from these methods.
These rules may seem a little esoteric but they avoid the sorts of shenanigans illustrated by my code question above.
DyslexicAnaboko - 11 Apr 2006 01:47 GMT Thanks for the long reply that won't help me with anything at all. I am just trying to get questions answered and I don't have time to have a flame war. So please, if you aren't going to help me understand what I did wrong and just ridicule me, I would rather you save your time and mine by not replying.
Thank you.
Roedy Green - 11 Apr 2006 05:11 GMT On 10 Apr 2006 17:47:20 -0700, "DyslexicAnaboko" <DyslexicAnaboko@gmail.com> wrote, quoted or indirectly quoted someone who said :
>Thanks for the long reply that won't help me with anything at all. I am >just trying to get questions answered and I don't have time to have a >flame war. So please, if you aren't going to help me understand what I >did wrong and just ridicule me, I would rather you save your time and >mine by not replying. He did not ridicule you. He pointed out why that code snippet was not idiomatic Java. Supposedly you are here to learn idiomatic Java.
When you post your code, you are implicitly asking for us to tell you how to improve it. You don't have to take the advice.
You have a lot of nerve to complain about someone going to the effort of telling you how to fix your code just because you are too lazy/busy to do the work.
It is kind of like going to the doctor and he recommends 30 minutes of exercise a day. You whack him over his head with his clipboard because you are too busy to exercise 30 minutes a day. That is not his fault.
Please see http://mindprod.com/jgloss/newsgroups.html#GIFTHORSE
 Signature Canadian Mind Products, Roedy Green. http://mindprod.com Java custom programming, consulting and coaching.
Alex Hunsley - 11 Apr 2006 11:59 GMT > Thanks for the long reply that won't help me with anything at all. It won't help you because of your attitude, not because there's no information there.
> I am > just trying to get questions answered and I don't have time to have a > flame war. So please, if you aren't going to help me understand what I > did wrong and just ridicule me, I would rather you save your time and > mine by not replying. Sheesh. I posted a good deal of useful information, containing *constructive* criticism. And you seem to think I'm just getting at you - I'm not. Do you know the different between constructive criticism and flaming?
I think perhaps you misunderstand the nature of getting help on Usenet a little: people don't fart about with couching feedback in the most sugar coated way possible. It's easier just to be direct with feedback and this is what people do. It doesn't mean they're being offensive or flaming you, it's just that it's the easiest way to do things. And if someone provides useful information back, even if it's not directly useful to you in what you're doing now, it doesn't make sense to gripe about it. You paid nothing for it, and griping makes the person who replied less likely to reply in the future. And people do often post feedback on aspects of your code that you weren't concerned about. Sorry if that irks your sense of entitlement, but that's how it is. It's free information, and can be useful to others, so don't moan about it.
As for saving your time and mine by not reply... The beauty of usenet is that even though you didn't get anything out of the reply/discussion, other people can. So it wasn't a waste of time, even though you yourself apparently didn't get anything out of it.
Thomas Weidenfeller - 11 Apr 2006 12:20 GMT > Thanks for the long reply that won't help me with anything at all. I am > just trying to get questions answered and I don't have time to have a > flame war. So please, if you aren't going to help me understand what I > did wrong and just ridicule me, I would rather you save your time and > mine by not replying. If you can't stand discussions, don't ask in a discussion group.
/Thomas
Tom Leylan - 10 Apr 2006 05:46 GMT I would say it sounds like you are describing a modal dialog box.
http://java.sun.com/j2se/1.3/docs/api/java/awt/Dialog.html
Also you may want to add a Validate() method to your ClassA (rather than count on checking things when the dialog closes.) This could be used by your dialog so it wouldn't have to close and reopen in the event that the account/password is wrong. You can for instance give the user 3 tries without closing your modal dialog window.
>I am having a problem that has really got me stuck and I think it is > because I am going about it incorrectly. [quoted text clipped - 36 lines] > I would greatly appreciate it if someone could help me with this > because I am at total loss. DyslexicAnaboko - 10 Apr 2006 16:34 GMT Okay, I think you got the classes mixed up, but you say to put a validate method in my GUI class? I'll try that.
As for the modal dialog box, thanks for the suggestion, but I don't think I will be able to do that since I am using Net Beans for creating all of my GUI. Which visually, it does nicely, but in my opinion the code it generates is sloppy. Thanks anyhow though =).
Oliver Wong - 10 Apr 2006 22:28 GMT > Okay, I think you got the classes mixed up, but you say to put a > validate method in my GUI class? I'll try that. [quoted text clipped - 3 lines] > all of my GUI. Which visually, it does nicely, but in my opinion the > code it generates is sloppy. Thanks anyhow though =). If NetBeans won't let you use modal dialog boxes, throw away NetBeans. Seriously. Modal dialog boxes are a pretty important topic in GUI design. They specifically address the problem you're trying to solve (that is, display a dialog box, and *WAITING* until the user responds to the dialog box before proceeding).
More likely, there's a way to get NetBeans working with modal dialog boxes (or else it'd be a joke IDE instead of a serious one), you just gotta figure out how. I don't use NetBeans so I don't know how either. Perhaps another poster more familiar with NetBeans can chime in here?
- Oliver
DyslexicAnaboko - 11 Apr 2006 01:36 GMT Will do, yeah I am very new at NetBeans, it was recommended to me since it is very easy to create GUI with it. More than likely it does have modal, I just meant that it will do what does, I am not in control of what it uses, I am using it because I know squat about formatting. I will look around to find out more about that, but right now I am just using a very simple JFrame as a test, I am not actually using the NetBeans GUI. That could also be the problem.
hiwa - 10 Apr 2006 06:05 GMT In the class A, you should instantiate the GUI and do nothing thereafter. Basically, you would do in the A_GUI class: ---------------------- loginButton.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ myClassAobject.validate(pwfield.getText(), idfield.getText()); } }); ---------------------- Above is too simple a code to be used in a production code. But I believe you could get the point.
DyslexicAnaboko - 10 Apr 2006 16:42 GMT I see what you are saying, and I think I tried doing something like that, but is it possible to send an instance of the current class to another class so that a new class is not instantiated?
In other words:
Is it possible to do this:
class A { public A() { //Constructor B otherClass = new B() ;
otherClass.getInstance( this ) ; }
public static void main( String [] args ) { A myA = new A() ; } }
class B { public B() { //Constructor }
public void getInstance( A fromA ) { //does something with class A instance } }
Is this what you are talking about?
Oliver Wong - 10 Apr 2006 22:29 GMT >I see what you are saying, and I think I tried doing something like > that, but is it possible to send an instance of the current class to [quoted text clipped - 32 lines] > } > } This is possible. Have you studied "static" methods yet? If so, just slap the static keyword in front of getInstance().
- Oliver
DyslexicAnaboko - 11 Apr 2006 01:38 GMT Yes I am familiar with static methods. Great I wasn't aware of that then, I will indeed use this idea if I am pressed to use it. Thank you.
DyslexicAnaboko - 11 Apr 2006 01:42 GMT Mr. Wong, you seem to be very good at this, possibly you can help me out with another problem I just ran into:
Is it possible for a class inside of a package to access classes outside of its package?
I do not know how to do this and I have been trying to find it via google but no luck at all.
If you could unlock that mystery it would help me a great deal.
Thank you for your help thus far.
Bjorn Abelli - 11 Apr 2006 09:44 GMT "DyslexicAnaboko" wrote...
> Is it possible for a class inside of a package to access > classes outside of its package? Of course, but only if those other classes belongs to another *named* package.
> I do not know how to do this and I have been trying to find it via > google but no luck at all. I believe you've already done that.
Not that you showed those parts of your own code, but I guess you've used the "import" statements?
That's how it's done.
// Bjorn A
Timo Stamm - 11 Apr 2006 10:02 GMT DyslexicAnaboko schrieb:
> Mr. Wong, you seem to be very good at this, possibly you can help me > out with another problem I just ran into: Hm. I'm not Oliver. Do you accept an answer from me too?
> Is it possible for a class inside of a package to access classes > outside of its package? Yes.
> I do not know how to do this and I have been trying to find it via > google but no luck at all. That's probably because the question is so very basic. Have you ever learned the language basics? This tutorial from sun should help you out:
http://java.sun.com/docs/books/tutorial/java/index.html
Timo
Oliver Wong - 11 Apr 2006 15:07 GMT > Mr. Wong, you seem to be very good at this, possibly you can help me > out with another problem I just ran into: [quoted text clipped - 8 lines] > > Thank you for your help thus far. As other have mentioned the way to do it is with an "import" statement. At the top of your class file, you write "import" followed by the fully qualified name of the class. For example, if I wanted to make the class "ArrayList" in the package "java.util" available to my file, even though my file isn't part of the "java.util" package, I'd write "import java.util.ArrayList;"
Note that this only works if the class I'm trying to import is part of a package. If you have "packageless" classes, then you can't import them.
- Oliver
DyslexicAnaboko - 11 Apr 2006 15:40 GMT I'm glad everyone thinks I am a beginner and I know I am at fault for not explaining my problem fully. I know what an import is, that is not the problem. I know how to import a class from a package. All I was asking was whether or not a class inside of a package that I myself created would be able to access a class outside of its package that I, again, myself created. This is not a 1 2 3 operation. There is no java.util.classIjustCreated, that only works for when you are using packages and classes from java or if you create your own, but I am not going to do that.
>From what I understand, people are saying that packages can access one another.
So lets say I have:
package alpha ; package beta ;
and they both reside in C:\greekStuff\
then technically any of the classes inside those packages will be able to: A. Import each other's package B. Since the package is imported use the classes inside of it.
=================================================== However, this below is what I am asking and I am afraid won't work:
Okay, again lets say I have:
package alpha ; class beta ;
and they both reside in C:\greekStuff\ meaning their file paths are: C:\greekStuff\alpha\ (alpha classes in here) C:\greekStuff\beta.java
Then what I want to do is:
A. let a class inside of the alpha package be able to use class beta. To be more clear, I want alpha classes to be able to access methods in class beta. Create objects and do what ever you would normally be able to do if you just had two classes in a folder together.
For the people who are only paying attention to how I phrased everything, tell me what you don't understand and I will elaborate again the best I can.
Steve Wampler - 11 Apr 2006 15:48 GMT > However, this below is what I am asking and I am afraid won't work: > [quoted text clipped - 18 lines] > everything, tell me what you don't understand and I will elaborate > again the best I can. This will work fine as long as you have C:\greekstuff\ on your classpath. Java will look for classes and packages in the directories on your classpath.
Steve Wampler - 11 Apr 2006 17:46 GMT >> A. let a class inside of the alpha package be able to use class beta. >> To be more clear, I want alpha classes to be able to access methods in >> class beta. Create objects and do what ever you would normally be able >> to do if you just had two classes in a folder together. ...
> This will work fine as long as you have C:\greekstuff\ on your > classpath. Java will look for classes and packages in the > directories on your classpath. Sorry. I'm wrong (failing memory). You can't do this without putting class beta inside a named package, as others have said.
Oliver Wong - 11 Apr 2006 17:28 GMT > I'm glad everyone thinks I am a beginner and I know I am at fault for > not explaining my problem fully. I know what an import is, that is not [quoted text clipped - 5 lines] > packages and classes from java or if you create your own, but I am not > going to do that. I believe my post, and at least one other post, mentioned that you cannot import a class if it's not part of a well specified package. This is one of the reasons it's recommended that you always put your classes in packages.
>>From what I understand, people are saying that packages can access one > another. [quoted text clipped - 10 lines] > A. Import each other's package > B. Since the package is imported use the classes inside of it. Technically, you don't import packages; rather you import classes. With Java 1.5, there's something called "static import" which lets you import static methods, but that's a completely different topic. When you see something like "import java.util.*", I'd think of it NOT as importing the "java.util" package itself, but rather as importing all the classes within that package.
> =================================================== > However, this below is what I am asking and I am afraid won't work: [quoted text clipped - 15 lines] > class beta. Create objects and do what ever you would normally be able > to do if you just had two classes in a folder together. Yes, this won't work. You need to put class "beta" in a package (which can also be called "beta" if you want). Note that it's a good idea to start your class names with an uppercase letter (e.g. "Beta"), and your packages with a lowercase letter. So if you put class "Beta" in a package called "beta", then to access it from within package "alpha", you'd have a line like "import beta.Beta;"
- Oliver
Roedy Green - 11 Apr 2006 19:28 GMT > Note that this only works if the class I'm trying to import is part of a >package. If you have "packageless" classes, then you can't import them. Except for very simple test classes you always put them in a package and import. see http://mindprod.com/jgloss/package.html http://mindprod.com/jgloss/import.html
 Signature Canadian Mind Products, Roedy Green. http://mindprod.com Java custom programming, consulting and coaching.
Thomas Fritsch - 11 Apr 2006 17:07 GMT > Is it possible for a class inside of a package to access classes > outside of its package? [quoted text clipped - 3 lines] > > If you could unlock that mystery it would help me a great deal. Sure it is possible. Actually it is so common, that every real-life program does it all the time.
Here is an example:
// file pkg1/A.java package pkg1; import pkg2.B;
public class A { public doSomething() { B b = ...; // get or create an instance of B b.doSomethingElse(); } }
// file pkg2/B.java package pkg2;
public class B { public doSomethingElse() { //... } // ...other methods and constructors }
All this is described near the beginning of every good java text-book. It is therefore important to work through the basics from the very beginning, instead of jumping into the advanced features first. (By the way: I don't mean this as an offence, but as an honest recommendation how to proceed.)
 Signature "Thomas:Fritsch$ops.de".replace(':', '.').replace('$', '@')
DyslexicAnaboko - 11 Apr 2006 18:06 GMT None taken, I know what you mean, its just that I am taking this class that doesn't really care whether or not you have learned this much yet. I am not familiar with all these things, so it is good to learn, that is why I ask questions. I am taking Software Engineering and I had to learn a lot on my own to get my program to work, nothing I learned in the other three classes I took previously. I always try to keep up with these things, but it is only done through practice.
So thanks to everyone who is helping me, I really do appreciate it.
hiwa - 11 Apr 2006 01:31 GMT > I see what you are saying, and I think I tried doing something like > that, but is it possible to send an instance of the current class to [quoted text clipped - 10 lines] > //Constructor > B otherClass = new B() ; B otherClass = new B(this) ;
> otherClass.getInstance( this ) ; > } [quoted text clipped - 8 lines] > class B > { A insA;
> public B() public B(A a)
> { insA = a;
> //Constructor > } [quoted text clipped - 7 lines] > > Is this what you are talking about?
Free MagazinesGet these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...
|
|
|