Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
zootm
Aug 8, 2006

We used to be better friends.
I hear good things about Google Guice. Spring is also OK, but if you're not using any of their IOP stuff the standard way of using it will drown you in unnecessary XML, whereas the annotation version buys you very little over standard good programming practice. I've not used Guice, either, though, so no guarantees it's actually any better.

For what it's worth I'm of the opinion that Scala (another JVM language) would make an excellent, type-safe configuration language for Java. With type-inference it's considerably terser than Java or XML, the very basic language features which you need to construct the items are no more complex than learning a set of annotations, and it'll enforce all (I think) of Java's type constraints so you don't get the exciting runtime problems due to erasure that you get with Spring XML.

Adbot
ADBOT LOVES YOU

necrobobsledder
Mar 21, 2005
Lay down your soul to the gods rock 'n roll
Nap Ghost

TRex EaterofCars posted:

Spring has a DI framework and I've found it decently powerful. With annotations it's not too bad to use, and configuration with Groovy is pretty easy.
I first thought about using Spring but umm... that's out of the picture for us given it's like taking a nuclear bomb strapped to a hammer when I just want a nailgun... unless I can completely strip out everything from Spring besides its DI framework. Groovy is currently out of the picture due to approval process issues that would keep me from doing any work for months or waste months of work if it was rejected.

TRex EaterofCars posted:

To answer your last question, do you have an example of what you're trying to do? If I understand you correctly, you want to do something similar to what Grails does. Grails (uses Spring) will load (and reload) arbitrary classes based on className by introspecting all classes in a given location. The "rules" are basically that the classes have to exist in a certain location. I'm sure you could do something similar.
Sounds useful, but related to what I said above, Grails is also likely a no-go. Also, it goes beyond class-loading - the class-loading is the trivial part for what I'm trying to do, in fact. I don't think I made myself terribly clear, so I'll try to show the gist of what we're trying to do.

==Scenario==

We have N classes with some similar looking method signatures:
pre:
package foo1;
public class A {
  public foo1.TypeA method1(..){..}
  public foo1.TypeB method2(..){..}
}

package foo2;
public class B {
  public foo2.TypeA method1(..){..}
  // method2 from A is not here
}
TypeA, for the sake of example, is actually identical across both packages. TypeB does not exist in the foo1 package.

We (try to) generate an interface with an offline code generator:
pre:
public interface IAB {
  public ITypeA method1(..){..} // invokes either A or B's method1 and returns an object that implements ITypeA, namely foo1.TypeA or foo2.TypeB
  public ITypeB fromA_method2(..){..} // 
}
... that is used by a generated factory class as follows (.
pre:
public class AB {
  public IAB newInstance(int version){
    switch (version){
      case VERSION_A:
        return newInstanceof_A_via_reflection();
      case VERSION_B:
        return newInstanceof_B_via_reflection();
      default:
        throw new FuckinNoobException();
    }
  }
}
What I want to do is use the factory in this manner:
pre:
public static void main(String[] args) {
    int version = Integer.parseInt(args[0]);
    IAB foo = AB.newInstance(version);
    foo.method1(..);
    if (version == WEIRD_VERSION)
      foo.fromA_method2(..);
  }
}
The basic idea is that the generated interface (perhaps abstract class?) IAB is the union of the methods of A and B with the disjoint set of methods still being accessible through that interface. Interface IAB could be the delegate for n many different classes with method1 possibly disappearing. A and B may be modifiable by hand, but there are a lot of classes and lots of methods per class. I'm actually concerned we will hit the maximum number of methods available for a class by the JVM and need to rethink this through (yes, that many classes, that many methods).

We're currently running a reflection service that resolves type references across multiple packages, resolves dependencies, creates interfaces to union them per roughly congruent class (we supply corresponding classes via canonical names), and generates factory classes and methods that have the sort of usage (poorly) shown above. I'm looking for something more elegant, documented, and flexible than what we have.


If you're curious about what beast might warrant all this, I'm trying to wrap an API that is evolving and I can never get rid of old versions nor their previous behaviors but somehow must provide access to all of them from a single API without incurring massive maintenance problems and to provide something concrete to quantify to other API developers how unstable their APIs are for their customers (political leverage on top of technical reasons - what's not to gain?). As new versions come up, we'd like to make adding support for the new API version's methods easier and to minimize memory footprint that would come with statically loading all the classes. So during runtime I pass the version number to be used to a factory that classloads the appropriate version of the library from disk and runs the underlying method or screams "not available in this version" if it's been idiotically removed. We'd like to have some compile-time verification of our unified API as well. Furthermore, I have maybe 10 or so of these API petting zoo collections to maintain... and growing.

zootm posted:

it'll enforce all (I think) of Java's type constraints so you don't get the exciting runtime problems due to erasure that you get with Spring XML
From what I've been reading about Scala, its type constraint system can be just as constrained as Java and more versatile. In fact, its lower type bound system is precisely what I want without going into full-on Ruby style duck typing + dynamic typing, which makes compile-time type checking less than useful. Java's typing system bugs the hell out of me, so I'd like to try something else, but as mentioned above, it's not exactly easy to do.

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

necrobobsledder posted:

Crazy poo poo.

Holy poo poo... Well, you *can* pull Spring apart, it's pretty modular.... but I don't think I'd try to do what you are doing with it.

Is there any reason you can't just bundle revisions of the APIs in individual jars and dynamically classload them depending on the version? You could then introspect the classes made available by that classloader (I found a particulary neat way of doing this just now), and make your interfaces that way. Then you don't have to play traffic cop. Or perhaps I still don't get it :smith:

necrobobsledder
Mar 21, 2005
Lay down your soul to the gods rock 'n roll
Nap Ghost

TRex EaterofCars posted:

Is there any reason you can't just bundle revisions of the APIs in individual jars and dynamically classload them depending on the version? You could then introspect the classes made available by that classloader (I found a particulary neat way of doing this just now), and make your interfaces that way. Then you don't have to play traffic cop. Or perhaps I still don't get it :smith:
We basically do that already. Like I said, messing with clever classloaders doesn't help with resolving the methods from version to version that is the hard part - it resolves package name conflicts, but it gets complicated if you need to unload a class, for example.

My job is to review APIs, package them into a unified API convention system, test the bejesus out of them, and play traffic cop among the different API versions and for different API categories. Imagine you're trying to keep every copy of PHP since 2.0, remove / delegate away redundant functions, and make a single API that you call the "golden version" of PHP that's distributed to PHP developers. Given how lovely PHP's APIs are, this has some value to anyone that must use PHP but hates its APIs.

Oh, I took a look at Spring and it won't suffice for what we're trying to do - we'd have to generate XML instead of Java code like we do now basically. We're too far in the realm of "Java sucks for us, let's rewrite it" territory for it to work probably anyway.

Twitchy
May 27, 2005

I'm implementing a database based on the functional data model and I've got a Map which contains an attribute as it's key, and a List of Objects as it's value (representing a table).

I'm trying to get constraints working and am completely stuck on checking that attributes are unique when more than 1 attribute map key is involved. Constraints can be added after settings up the tables etc. so the current data needs to be validated before the constraint is accepted.

For example I might have an entity (basically a table) with 2 attributes Forename and Lastname, which will have keys and a List of the values.

code:
Position in Lists    Forename    Surname <<< Map keys
0                    John        Smith   <<< List<Object> values
1                    John        Doe
2                    John        Smith   <<< Should fail because of duplicate
Obviously checking one attribute list for duplicates is easy but I'm not sure how to go about it if there are multiple attributes involved. I don't really need Java code or anything I just need a point in the right direction because I'm sure there's probably an easy way to do it but I just can't see it :(.

code:
int count = 0;
for (Map.Entry<Attribute, List<Object>> records :
        entity.getRecords().entrySet())
    if (attributes.contains(records.getKey())) {
        List<Object> attributeValues = records.getValue();

        if (attributeValues.size() > 1) {
            for (int i = 1; i < attributeValues.size(); i++) {
                if (attributeValues.get(0).equals(attributeValues.get(i))) {
                count++;
                break;
            }
        }
    }
}

if(count >= this.attributes.size()) {
    System.out.println("DEATH");
}
The code above is just to give an idea of what I've tried to do but if it doesn't make sense it's not really important. Basically what I have so far is it works but both a forename and surname exist e.g. John Smith, Ted Danson, if you try and add Ted Smith it doesn't work because it's not done properly.

Edit: gently caress this makes no sense, basically if you have 2 or more Lists which have Objects related by their insertion order (forename, surname etc) what's the best way to see if there are any duplicates across the lists?

Twitchy fucked around with this message at 22:12 on Feb 2, 2009

Boo This Man
Mar 25, 2008

I'm trying to get the length of 3 characters on 3 seperate strings. But I can't figure out how to use the .length after declaring a string.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

Logostomp posted:

I'm trying to get the length of 3 characters on 3 seperate strings.

What do you mean by "the length of 3 characters"? Do you mean the "graphical width", i.e. the amount of horizontal space the characters take up when rendered in a particular font?

Boo This Man
Mar 25, 2008

rjmccall posted:

What do you mean by "the length of 3 characters"? Do you mean the "graphical width", i.e. the amount of horizontal space the characters take up when rendered in a particular font?

Length of 3 seperate words. The amount of characters in each word.

Mill Town
Apr 17, 2006

Logostomp posted:

Length of 3 seperate words. The amount of characters in each word.

Use string.split to split the string into a list of words, the loop through the list of words and get the length of each string.

e: of

Mill Town fucked around with this message at 18:55 on Feb 3, 2009

zootm
Aug 8, 2006

We used to be better friends.

Twitchy posted:

I'm implementing a database based on the functional data model and I've got a Map which contains an attribute as it's key, and a List of Objects as it's value (representing a table).

...
This is a pretty horrible data structure for what you're wanting to do, but the simplest way to do it is probably build up a Set with Lists representing the rows, if you don't want to change to something which represents rows directly.

Something like this would work, although it's pretty horrible (it'd be easier if you had closures and stuff but let's not dwell on that, it's a horrible solution regardless):
code:
// Grab the iterators for each of the "columns" so that we can iterate them all at once.
// Wrapping in some meta-iterator which returns the rows might be a better way to do this
// "in general"
List<Iterator<Object>> keyColumnIterators = new ArrayList<Iterator<Object>>();
for( Attribute keyAttribute : attributes ) {
  keyColumnIterators.add( records.get( keyAttribute ).iterator() );
}

Set<List<Object>> keysEncountered = new HashSet<List<Object>>();
while( allHaveNext( keyColumnIterators ) ) {
  List<Object> thisKey = new ArrayList<Object>( );
  for( Iterator<Object> keyColumnIterator : keyColumnIterators ) {
    thisKey.add( keyColumnIterator.next() );
  }
  if( keysEncountered.contains( thisKey ) ) {
    throw new RuntimeException( "Duplicate key encountered: " + thisKey );
  }
  keysEncountered.add( thisKey );
}
With this utility method:
code:
private <T> boolean allHaveNext( List<Iterator<T>> iterators ) {
  for( Iterator<T> iterator : iterators ) {
    if( !iterator.hasNext() ) {
      return false;
    }
    return true;
  }
}
If you want to check for counts of duplicates or not bomb out you could use a Map or something keyed on the constructed keys.

Boo This Man
Mar 25, 2008

Mill Town posted:

Use string.split to split the string into a list of words, the loop through the list of words and get the length of each string.

e: of

Need to use a if else statement. The question states, "Write a program that reads three strings from the keyboard. Although the strings are in no particiular order, display the string that would be second if they were arranged lexicographically.

I don't need somebody to give me the answer, but give me some sort of idea where to go with this. Here's what I have so far.


package project5;

import java.util.Scanner;

public class Main {


public static void main(String[] args) {


Scanner keyboard = new Scanner(System.in);

String s1, s2, s3;
System.out.println("Please enter 3 words");

s1 = keyboard.nextLine();
s2 = keyboard.nextLine();
s3 = keyboard.nextLine();

System.out.println("Now I will show you the second longest string");





}

}

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

Logostomp posted:

Although the strings are in no particiular order, display the string that would be second if they were arranged lexicographically.

I'm not sure what you think length has to do with lexicographic ordering — to the extent it matters here, "lexicographic" is just a fancy word for "alphabetical". Unless you've been asked to do something fancier, just use the compareTo method.

dancavallaro
Sep 10, 2006
My title sucks

Logostomp posted:

...unformatted code...

Use the code tags to format your code:

code:
package project5;

import java.util.Scanner;

public class Main {

   public static void main(String[] args) {

      Scanner keyboard = new Scanner(System.in);

      String s1, s2, s3;
      System.out.println("Please enter 3 words");

      s1 = keyboard.nextLine();
      s2 = keyboard.nextLine();
      s3 = keyboard.nextLine();

      System.out.println("Now I will show you the second longest string");
   }
} 

Boo This Man
Mar 25, 2008

rjmccall posted:

I'm not sure what you think length has to do with lexicographic ordering — to the extent it matters here, "lexicographic" is just a fancy word for "alphabetical". Unless you've been asked to do something fancier, just use the compareTo method.

So the word would have to be arranged from A to Z. Like a word hot would be before the word not?

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

Logostomp posted:

So the word would have to be arranged from A to Z. Like a word hot would be before the word not?

Right, and "hop" before "hot", and "hot" before "hottentot". Something worth noting: compareTo's algorithm is based purely on the numeric values of characters, and the capital (English) letters happen to all be numerically less than the lowercase letters, so it will also put "Hot" before "abracadabra" — but chances are good that your professor will be overjoyed if you can manage the if statements and certainly will not quibble over case-sensitivity.

lamentable dustman
Apr 13, 2007

ðŸÂ†ðŸÂ†ðŸÂ†

rjmccall posted:

Right, and "hop" before "hot", and "hot" before "hottentot". Something worth noting: compareTo's algorithm is based purely on the numeric values of characters, and the capital (English) letters happen to all be numerically less than the lowercase letters, so it will also put "Hot" before "abracadabra" — but chances are good that your professor will be overjoyed if you can manage the if statements and certainly will not quibble over case-sensitivity.

compareToIgnoreCase() exists for that reason :)

1337JiveTurkey
Feb 17, 2005

Another alternative is to call java.text.Collator.getInstance() to get a Collator object which you can call myCollator.compare(string1, string2) and get the correct behavior for where you live.

Mustach
Mar 2, 2003

In this long line, there's been some real strange genes. You've got 'em all, with some extras thrown in.
That inspired me to look at the javadoc for compareToIgnoreCase(), which says this:

quote:

where case differences have been eliminated by calling Character.toLowerCase(Character.toUpperCase(character)) on each character
What does the double case change accomplish? Presumably it's to protect against something, but I can't think of anything.

Boo This Man
Mar 25, 2008

rjmccall posted:

Right, and "hop" before "hot", and "hot" before "hottentot". Something worth noting: compareTo's algorithm is based purely on the numeric values of characters, and the capital (English) letters happen to all be numerically less than the lowercase letters, so it will also put "Hot" before "abracadabra" — but chances are good that your professor will be overjoyed if you can manage the if statements and certainly will not quibble over case-sensitivity.

Sounds good. I will try this out. Thanks for the help.

zootm
Aug 8, 2006

We used to be better friends.

Mustach posted:

That inspired me to look at the javadoc for compareToIgnoreCase(), which says this:

What does the double case change accomplish? Presumably it's to protect against something, but I can't think of anything.
It'll be an internationalisation thing. I imagine the case conversion is not necessarily reflexive.

1337JiveTurkey
Feb 17, 2005

zootm posted:

It'll be an internationalisation thing. I imagine the case conversion is not necessarily reflexive.

Yeah. It handles the German esszett, or ß character. When capitalized, it turns into SS, which then lowercases back to ss, the equivalent without the ligature. So Straße becomes STRASSE becomes strasse. Note that not only is this irreflexive, it gets longer in the process, potentially overflowing buffers for the unwary.

maskenfreiheit
Dec 30, 2004
...

maskenfreiheit fucked around with this message at 03:43 on Sep 29, 2010

Boo This Man
Mar 25, 2008

Another question. I'm almost done with this other Java question. I need to know how to do multiples of numbers. Like the input has to be a multiple of 5, the rest would be an error, like a 3, 1, 6, ect.

Also has to be greater than or equal to 25 and less than or equal to 100 and a multiple of 5. I've got 2 out of 3 done.

Boo This Man fucked around with this message at 06:20 on Feb 5, 2009

1337JiveTurkey
Feb 17, 2005

It uses an operator, I can tell you that much. It also doesn't use the result of the operator directly, but compares it to another number. If they're equal, it's divisible.

Boo This Man
Mar 25, 2008

Nevermind, I figured it out.

Mill Town
Apr 17, 2006

GregNorc posted:

I'm reading head first java... they had this optional exercise messing around with the sound API... it's a really basic program, it's supposed to just play 1 note, to get used to the commands needed.

I got it to compile, but when I run it from the command line, OSX switches to some sort of java app with the same name as the file (instead of just staying in terminal like usual), and no sound plays. I've ruled out hardware issues (tried plugging in headphones, checked that volume wasn't muted)

Screenshot of error, since it's kind of hard to describe. Note how an app called miniminimusicplayer with a java icon has opened:

Click here for the full 1280x800 image.


Apparently MIDI just doesn't work in Java in later versions of OS X. Here's a piece of software that's supposed to fix that:
http://www.humatic.de/htools/mmj.htm

However, I tried installing this on my computer and running your program, and it didn't help. I think this software is mostly used for attaching hardware MIDI devices, and I can't find a software MIDI synth on my system at all. I was sure there used to be one in older versions of OS X.

Mustach
Mar 2, 2003

In this long line, there's been some real strange genes. You've got 'em all, with some extras thrown in.

1337JiveTurkey posted:

Yeah. It handles the German esszett, or ß character. When capitalized, it turns into SS, which then lowercases back to ss, the equivalent without the ligature. So Straße becomes STRASSE becomes strasse. Note that not only is this irreflexive, it gets longer in the process, potentially overflowing buffers for the unwary.
Those are the String methods you're talking about, though. compareToIgnoreCase uses the Character ones, which don't do those kinds of conversions.

maskenfreiheit
Dec 30, 2004
...

maskenfreiheit fucked around with this message at 03:44 on Sep 29, 2010

Mill Town
Apr 17, 2006

GregNorc posted:

poo poo. Pretty much the final three chapters, which deal with socket programming, swing, all the good stuff... they center around this beatbox app you make that keeps getting functionality on (like streaming over a network with sockets, or a GUI w/ swing)

poo poo

:(

This is just me talking out of my rear end here after some cursory googling, so don't get too discouraged yet. You could replace the javax bits with calls to the equivalent bits of mmj, or something like that.

Edit: and the software synth IS still in OSX, I just checked. I don't know how to call it from Java, though.

1337JiveTurkey
Feb 17, 2005

Mustach posted:

Those are the String methods you're talking about, though. compareToIgnoreCase uses the Character ones, which don't do those kinds of conversions.

OK, there's gotta be something really subtle going on there but at least in the case of Turkish, it'd map small i (no dot) to large I (no dot) back to small i (dot) and large I (dot) to large I (dot) to small I (dot) instead of the locale-specific way. Lots of programs break when run in the Turkish locale because they assume that every language with I and i map between the cases the same way as English.

Rekkit
Nov 5, 2006

I have a null pointer exception and can't for the life of me figure out what is wrong, could someone please help?

Exception in thread "main" java.lang.NullPointerException
at quiz.answers(quiz.java:77)
at quiz.main(quiz.java:20)

http://pastebin.com/m23bd1221

UNCUT PHILISTINE
Jul 27, 2006

I'm starting a simple project in Java (actually it's in clojure, but Java+swing libs will be used) to enter recipes and save them in a database, for the gui part, what would be the best widget to handle it? I was just reading over the docs and my head is spinning a bit.

It should be simple, just adding/removing lines of text (ingredients) and being able to access them easily by line is my only concern. Would JTextArea suffice?

covener
Jan 10, 2004

You know, for kids!

Sour Fish posted:

I have a null pointer exception and can't for the life of me figure out what is wrong, could someone please help?

Exception in thread "main" java.lang.NullPointerException
at quiz.answers(quiz.java:77)
at quiz.main(quiz.java:20)

http://pastebin.com/m23bd1221

line is the only thing you dereference on line 77. readLine() returns null at end of stream.

lamentable dustman
Apr 13, 2007

ðŸÂ†ðŸÂ†ðŸÂ†

Sour Fish posted:

I have a null pointer exception and can't for the life of me figure out what is wrong, could someone please help?

Exception in thread "main" java.lang.NullPointerException
at quiz.answers(quiz.java:77)
at quiz.main(quiz.java:20)

http://pastebin.com/m23bd1221

Sysout the string 'line' or something. It is probally null or ""

Rekkit
Nov 5, 2006

Ah I needed to add

inFile.close();
initFile();

in the previous method that referenced line. Thank you.

1337JiveTurkey
Feb 17, 2005

Without Pants posted:

I'm starting a simple project in Java (actually it's in clojure, but Java+swing libs will be used) to enter recipes and save them in a database, for the gui part, what would be the best widget to handle it? I was just reading over the docs and my head is spinning a bit.

It should be simple, just adding/removing lines of text (ingredients) and being able to access them easily by line is my only concern. Would JTextArea suffice?

Yeah. If you're really only looking for something simple for entering individual lines of text, you could just use a JList with some sort of customization for in-place editing. Using a single selection model and a JTextField for rendering on top of the active cell seems like a horrible hack but it should work in theory.

UNCUT PHILISTINE
Jul 27, 2006

JList looks like just what I'm looking for. Thanks!

Hardboiled Kid
Jul 27, 2001

This is my club avatar!
Retarded CS major here.

Is there anyway to use the JTextField class and Scanner class together? I'm looking at the API and I can't find a method to use here.

1337JiveTurkey
Feb 17, 2005

Trifling Fox posted:

Retarded CS major here.

Is there anyway to use the JTextField class and Scanner class together? I'm looking at the API and I can't find a method to use here.

Sorry for such a long post, but just knowing there isn't a way is only half the story. JTextField and other GUI objects work under a completely different principle than you're used to from writing apps that use Scanner and System.in. The way you're used to is you write a program that starts from the beginning of main() and you trace the flow of control all the way to the end. If the user hasn't entered a line on the console, the Scanner blocks (waits) until something happens and the flow of control stops.

Intuitively it feels like we should be able to make a program with a GUI which acts the same way but then the question arises: If I'm waiting for one thing but the user does something else, how can I react? There are three solutions: The first was making a seperate flow of control (thread) for everything. It sounds good in theory, but what happens if you press on one button before another's done processing? Very bad things, that's what. The only use of that solution was BeOS which had a reputation for being quick, responsive and buggy as gently caress.

The second option is to have one flow of control which doesn't wait for something to happen, it just loops over everything in the GUI to see if something changed (polling) but never waits for anything to happen. Embedded computers like in cars use this because it doesn't take a lot of elaborate software or specialized hardware to make it work.

Finally, we can have one flow of control which waits for anything to happen at all, figures out what to do based on what happened, and then waits for the next event. It sounds painful to write code which can handle anything that a user can do in a GUI considering that there's gotta be hundreds of possibilities. Most modern OSes as well as Swing use this method, but they don't force you to write one big loop that does it all.

Instead, they have what's called the event dispatch loop or event dispatch thread. You create event listeners and register them with this loop. Event listeners have code that you want performed when some event happens, like when the user presses enter on a JTextField.

code:
public class ExampleAction extends java.awt.event.ActionListener {
	public void actionPerformed(java.awt.event.ActionEvent e) {
		// This only works when this event is registered on a JTextField
		JTextField field = (JTextField) e.getSource();
		// We get the text the user entered from the field
		String input = field.getText();
		// And then we empty the field out for the next time
		field.setText("");
		// Here's where you do what you normally would after myScanner.nextLine()
		// Once that's done, leaving this method is like calling myScanner.nextLine()
	}
}
Here's where it gets confusing to new programmers: You never actually call actionPerformed() and you never actually create an ActionEvent to send to it. Instead what happens is when the user presses enter on the registered JTextField the OS tells the event dispatch thread which then creates an ActionEvent and calls your registered ExampleAction with it. When you're done, the event dispatch thread waits for the next event. The flow of control as you're used to is completely upside down since instead of your code doing the looping and calling the scanner code, the Swing code is doing the looping and calling your code. Unfortunately this means that there's no good way to mix the two since they're totally and fundamentally incompatible.

Adbot
ADBOT LOVES YOU

ynef
Jun 12, 2002
Excellent post, 1337JiveTurkey!

It should also be noted that there is a nasty consequence to letting just this one thread handle all the events in Swing: if your event handling includes a lengthy operation (say, getting a file from a network location or calculating something that takes a while), that means that you have effectively prohibited the GUI from being responsive during that time. To avoid this problem, you must perform lengthy tasks in the background using another thread. Thankfully, there is a class for making this easy, called SwingWorker.

Read up on Concurrency in Swing, and really get comfortable with the concepts presented there. Obeying the rules there is crucial to making usable programs.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply