|
Trifling Fox posted:Retarded CS major 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:
|
# ¿ Feb 6, 2009 06:05 |
|
|
# ¿ May 12, 2024 08:39 |
|
If you create a HttpURLConnection from a URL (cast the regular URLConnection), that's a bit more high level and has convenience methods for HTTP-specific functionality.
|
# ¿ Feb 15, 2009 07:05 |
|
OK. The easiest way to do this is to break it up into two problems. First you need to distinguish where the start and end of a parseable command is. If the user is pressing enter after each command, then you really want to just get the next line rather than searching for tokens. There are several ways to do this, but one of the simpler ways is to just take System.in and then wrap it in a InputStreamReader and then a BufferedReader like so:code:
|
# ¿ Feb 20, 2009 06:04 |
|
That can be painfully slow if the number of items increases much beyond where it is. If you're looking for a shuffled list of numbers, then this should be what you need:code:
|
# ¿ Feb 21, 2009 00:46 |
|
JBoss uses the Log4J logging framework. You can find the configuration file for it in the config directory of your server. If you're just looking for calls to System.out, just make a subclass of PrintStream that wraps the real/current System.out and sends everything to it instead. Remember: System.out isn't final so you can replace it with whatever you want. You can set a breakpoint there or you can just create a Throwable, getStackTrace() it and get the second element. That's got the class, method, file name and line number (if you compiled those in) for whatever printed to System.out. edit: If you find the Log4J config file, you can filter specific packages IIRC so you can at least shut those ones that constantly spam poo poo in debug mode up.
|
# ¿ Feb 21, 2009 01:43 |
|
You've got the original list, an argument that's a copy of the original list, and an argument that's an iterator on the original list. The iterator is the only one you're currently using, but you actually don't want to pass it as a parameter. The simplest method for getting all of the possible anagrams is to start with the collection of letters and a blank string for the anagram so far and then go through all the words in the dictionary. If it doesn't fit, skip it. If it fits, then append it to the anagram so far. If the fit was exact, print it out and continue. Otherwise recurse with the remaining letters and the new anagram. It'll obviously be slow but there are a few techniques for speeding it up if you need them.
|
# ¿ Mar 13, 2009 04:15 |
|
Warblade posted:This question is kind of language agnostic, but I'm dealing with Java so maybe there's some kind of Java convention for doing this. Say you write a class that accepts some kind of listener. At some point you'll be iterating through all of your listeners to notify them that something significant happened. Maybe the method call is listener.sendEvent(). All event listeners in Java should derive from the java.util.EventListener interface, and all objects giving the specifics of a certain event should use the java.util.EventObject. Those are more markers than anything else, but they're what everyone expects for typing purposes. The javax.swing.event.EventListenerList can store listeners of multiple different types in one array and returns an iterator of only the type that you want when you pass it the corresponding class object. Normally that's wrapped so that there's a public addFooListener() method which adds a listener, a public removeFooListener() which removes the given listener, a getFooListeners() which returns an array of the registered listeners, and one or more protected fireFoo() methods corresponding to the events which the listeners can receive. These events should normally create a new object of the correct type, initialize it and then send it to all of the listeners. As a rule, the sender owns the event and the receivers shouldn't change it at all but this is by convention so the sender shouldn't create duplicates of any data it sends. Listeners should generally be quick and return immediately. Quick in GUI terms is actually a surprisingly long period of time, but never block on the event loop. You know when Windows says a program has stopped responding? Dollars to donuts some genius went and did that because no events deposited in the queue by the OS in the last five seconds have been retired. There are methods for only attempting to grab a resource which will just return false if they fail and can be used, but generally anything that needs to wait for something should be spawned off into a separate worker thread while everything else can safely be done in the main event loop. Two things to pay particular attention for are event loops and cascades where events trigger other events which can lead to a non-local infinite loop or just horrible performance as something gets triggered way too many times. I find that this often happens when there's both a 'real' model and another model which exists solely for the view and the controller and the programmer attempts to synchronize the two through events. Either use the default models to store the real data or wrap the real data structures in the appropriate interfaces in that case. Finally watch out for keeping references in listeners to other parts of the GUI. It's better to send everything through the associated EventObject so that there aren't any spurious references keeping things from being garbage collected.
|
# ¿ Apr 9, 2009 04:12 |
|
A using or with block would go a long ways to making that stuff sane. On the plus side it does look like at least the null pointer checks are going to be less painful in Java 7 since they're certain at this point that it'll have the .? short-circuiting dereference operator. istream.?close() would call the method only if the stream isn't null. They'll also add another assignment operator foo ?= bar which assigns bar to foo iff foo is null. Also on the topic of closing streams, they've got some neat new annotations for IDEs that can be added to parameters in method signatures to tell whether stream arguments will be closed at the end of the method call or not.
|
# ¿ Apr 16, 2009 14:46 |
|
The lack of unsigned numbers don't bother me too much at least as far as work goes. There's two things which unsigned numbers provide: An implicit lower bound on possible values and twice the number of possible positive values. The implicit lower bound is nice, but it's no substitute for proper bounds checking every input. The extra positive range is pretty much illusory: If n bits isn't enough n + 1 bits won't be enough in practice. Any company can grow to or churn through 256 employees if they can do 128, and ~2 billion employees isn't any less laughable than ~4 billion. Y2038 fix proposals aren't talking about just using an unsigned number because even if it pushes things back until after almost everyone is dead, 64 bit just isn't that big of a deal these days. When I get an unsigned number smaller than 32 bits in some imported data, treating it as an int for internal calculations doesn't hurt anything as long as I remember its 'real' range for when it counts, such as writing it back out. Performing arithmetic on numbers that use the extra range is spotty since beyond multiplication possibly causing overflow, now addition and subtraction can as well. Since Java continues on the C tradition of not trapping them and letting the programmer sort it out, it's a whole extra can of worms dumped on top of everything else. That said, I'm extending an emulator someone wrote for the MIPS architecture to some other ones for fun and it seems like I'm doing a lot of ((long) foo) & 0x00000000FFFFFFFF. It's tedious at points but at least most operations are identical in practice so I can just add, shift or multiply and not give a gently caress since the only difference is the interpretation of the result.
|
# ¿ Apr 16, 2009 22:41 |
|
As far as I know using a date which could even remotely be construed as valid to stand in as an invalid date or null date is never considered a good practice. new Date(Long.MIN_VALUE) would be several hundred MYA. In this case just using null would do the exact same thing you're expecting.
|
# ¿ Apr 17, 2009 17:20 |
|
Honestly unless your output file is going to be absolutely MASSIVE, stick them into a LinkedHashSet<String> and just iterate through that when the input file is empty.
|
# ¿ Apr 17, 2009 23:18 |
|
Clock Explosion posted:Out of curiousity, why do you recommend a LinkedHashSet rather than some other data structure? LinkedHashSet enforces uniqueness while preserving the insertion order. It gives the exact same effect as searching through the output file every single iteration without the cost of O(n^2) IO operations. edit: Instead, there'd be O(n) IO operations and the hashset accesses won't even show up on a profiler.
|
# ¿ Apr 18, 2009 00:29 |
|
HFX posted:Yep. A set enforces uniqueness. That is why I used it. The iterator you get from it is guaranteed to be in order or insertion. See my code. Er, why bother with the removeDuplicatedLines() method then?
|
# ¿ Apr 18, 2009 01:02 |
|
StickFigs posted:I'm having a little trouble understanding your code, right now I'm trying to figure out how you output the populated LinkedHashSet to the .txt file. Looking at it now I see: That's foreach. It's a for loop which will go through every single item in a set, list, array or anything else that implements Iterator<T>. It automatically sets outputLine every time it loops through and terminates when it runs out of items.
|
# ¿ Apr 18, 2009 01:07 |
|
For the purposes of making a file uploader, a JNLP-launched applet would work. JNLP allows a slightly larger set of permissions than plain applets such as to create a file open dialog. https://jdk6.dev.java.net/plugin2/jnlp/
|
# ¿ May 27, 2009 18:31 |
|
krooj posted:Question - JavaFX is piqued my interest as a cleaner alternative to the poo poo-show that is AJAX, but I am wondering what the difference is between JavaFX and a regular ol' Applet. Any huge diff? It's got a more declarative language for making UIs and it's supposed to be multiplatform as well. As long as it doesn't depend on any libraries that wouldn't be available on a mobile platform, it'll work on that as well. It also supports WebStart so that it can be used as a standalone application by putting a JNLP file on the server.
|
# ¿ Jun 8, 2009 17:30 |
|
Here's a few possible things to look at in the base API:
I'd suggest avoiding anything related to Java Enterprise Edition, EJB or the like until you're thoroughly acquainted with the basics. There's also a huge number of open source projects to look through. Robocode in particular is a good choice for beginner programmers.
|
# ¿ Jun 19, 2009 06:31 |
|
rhag posted:To get what you want, you'll need to create a custom scrollable component (extents JPanel probably). That's one option. The other is to just drop a JPanel in there and put all of the components inside of that.
|
# ¿ Jul 17, 2009 00:00 |
|
Fehler posted:I would like to make a Java program extensible by allowing people to write their own classes (derived from a pre-defined class) which I would then load in my program. That way, I'm hoping to make it possible to add certain features without having to recompile the entire program, or even having access to the code. Every class file is effectively a dll. A classloader like a URLClassLoader is used to load the class from a Jar file, then the class can be instantiated through reflection and used normally.
|
# ¿ Jul 24, 2009 13:26 |
|
It's possible to make those <T extends Enum> into <T extends Enum & CostTypeInterface>. (Syntax might be off) The interface can have whatever methods you want for the user to implement, allowing for some specialized behavior.
|
# ¿ Aug 5, 2009 22:25 |
|
Relative paths are determined from the working directory where the java command itself is run. For IDEs this usually isn't inside of the source path. NetBeans and IntelliJ both use the project root directory, so try there. If you've got the file in the same directory as the .class file and you only need to read from it, it can be reached using ClassWork7.class.getResourceAsStream("tas.txt").
|
# ¿ Aug 7, 2009 09:18 |
|
Do you know the actual type of the array where you're calling it? The Collection.toArray() method takes an array of the type that you want and uses reflection to make a bigger one if it's not large enough.code:
Of course if you can't change it, things get messy. One possibility (haven't tested it but it should work) is to figure out the type based on the elements of the iterator. Keep in mind that this is mostly from memory written in an IDE called 'Firefox'. code:
|
# ¿ Sep 26, 2009 03:33 |
|
Fly posted:Could that be a byte-order mark (BOM)? http://unicode.org/faq/utf_bom.html#BOM It's the length of the encoded string in bytes. The actual string encoding isn't exactly UTF-8, but instead a modified version which preserves surrogate pairs and null characters without leaving any embedded nulls in the encoded bytes. That method is more for quick and efficient byte-for-byte precision in the deserialized data than it is for byte-for-byte precision in the serialized form.
|
# ¿ Oct 21, 2009 00:47 |
|
Install a custom SecurityManager just before the code is called such that checkExit() throws a SecurityException every time. Then in the finally block remove the manager so that you can actually exit normally. If you reach the catch block with a SecurityException, some brilliant soul decided to handle an error by calling Runtime.exit() or Runtime.halt().
|
# ¿ Nov 3, 2009 23:18 |
|
Rsugar posted:I'm making a tile-based game, and I'm a little confused on this: You can just make a Tile object which has the appropriate getters and setters for the basic attributes. Tile-specific behavior can be handled through subclassing. Then just stick them into your array and just look it up using the coordinates when you need them. edit: Are you having trouble with array lookups?
|
# ¿ Nov 8, 2009 03:37 |
|
timecircuits posted:I have an interview on Thursday for an internship wherein I would be writing Java. Java is significantly different from C++ in how it's used so it's hard to just give a 1:1 mapping beyond libraries like SAX or OpenGL/JOGL. The official tutorials keep the basic language syntax to one section of one tutorial so you can just skip the stuff on basic flow control. You'll probably want to understand how Java handles exceptions differently as well as how it handles inheritance but those are both less complex than C++. The tutorials also cover a lot of the basic libraries that you'll want to know. Focus on having a solid understanding of the basics and don't worry about the more complex APIs. There's always the risk that you'll run into some insane interviewer who considers knowing how to diagnose bizarre classpath issues running WAS 6.1 on Solaris to be fair game but you can't plan for every contingency. On the other hand it's much more likely that they'll want someone who understands the difference between a List<String>, a LinkedList<String> and an ArrayList<String> and which can be used in place of which.
|
# ¿ Nov 10, 2009 20:52 |
|
MEAT TREAT posted:I was going to say that I've never found a use for a LinkedList over an ArrayList, but then I remembered that it implements the queue and deque interfaces. It's also good for data structures 1 homework where your professor thinks your name is Josh Bloch.
|
# ¿ Nov 10, 2009 22:53 |
|
ynef posted:In math, you'd probably get away with ceil(log2(given_number)), but Java doesn't have a general logarithm function like that (just the natural logarithm). You'd have to use the Change of Base theorem to compensate. ceil(log2 n) = 32 - Integer.numberOfLeadingZeroes (n - 1) for all positive n.
|
# ¿ Nov 24, 2009 19:12 |
|
This code is under the presumption that you're looking for there to be many possible implementations of the abstract class but want only one at runtime. Using System.getProperty() isn't necessary but fits with established practice in the libraries. In order to make this work, you'll also need to make sure that you've got a META-INF/services directory in the JAR file with the children of the Connection class listed.code:
|
# ¿ Jan 27, 2010 05:24 |
|
amr posted:I'm building the GUI for a program I'm working on and I've hit a bit of a problem. CardLayout on the right hand side to swap things, then put a TreeSelectionListener on the tree to be informed whenever the user picks something different. Usually you'd make or extend your own tree model to store the information about the editor that should be shown for that tree node.
|
# ¿ Feb 11, 2010 14:53 |
|
amr posted:That's what I'm doing currently. CardLayout to swap the panels, and extending my own tree, the problem is I'm not sure how to store nodes in the JTree and then how I should load the correct panel. Currently I've got a big switch statement and I'm swapping based on the node's toString() (not the best idea, I know, that's what I'm wanting to change it) Swing is MVC-oriented, so the idea is that your data should either implement the TreeModel or TreeNode interfaces or have that as a front end that ultimately manipulates them. Then it's not really a question of how you store the nodes because then the JTree is just a window (the View) onto your Model. The tree then by default displays the toString() of the nodes themselves and you can have all the data you need inside of the nodes. To pick what to display there's a few ways. The most straightforward method of just having a method that gets the panel itself on the node has the problem that it sticks a dependency on your View in the Model when generally it should always be in the other direction. Using a map of node classes to right hand panels could also work. The selection listener would then get the selected node and look up its class to find the correct right hand panel, then pass the node to the panel in some initialize method. That can be made as simple or as complex as you like.
|
# ¿ Feb 12, 2010 07:02 |
|
amr posted:Thanks for your advice, although some of that went way over my head :P This is my first time actually doing a proper user interface for my program. I'm still not quite sure how to do it. I was thinking of trying to use reflection or having a static getInstance() method. Do you know of any material I can read so I know what I'm doing? Cheers These two articles give a 10,000 foot overview of Swing and MVC: http://en.wikipedia.org/wiki/Swing_(Java) http://en.wikipedia.org/wiki/Model%96view%96controller Here's the standard tutorial which covers how to use Swing in depth: http://java.sun.com/docs/books/tutorial/uiswing/ To answer your question, it really depends on what your requirements are. For the one-off utilities that I've worked on, just slapping a getPanel() method on the node itself is often perfectly adequate even if it tightly couples some aspects of the program. For the flagship application I work on, it's a full-fledged subsystem with dozens of pluggable editors available for various combinations of nodes along with stuff like dynamic per-seat licensing. If I were to remove the huge amount of legacy cruft on it and pare it down to its core, that'd be basically the controller for the right hand panel asking all of the editors "can you edit this set of nodes?" and then adding a tab for each one that returns true. It works well with plugins and is pretty much instantaneous even with well over 100 different possible tabs since they're just looking at the number of nodes as well as their class.
|
# ¿ Feb 13, 2010 22:21 |
|
ynef posted:Well, you can always over-engineer it by using a ScheduledExecutorService if you want, but what you had should work too. I'd say that 90% of my stress at work is from people ignoring established solutions to complex problems in favor of their own hacked together solutions that mistake their inability to understand the entirety of the problem for an eye for elegance. It's one loving object with a one argument constructor and a method that takes the exact same Runnable he'd have to write otherwise plus however long he wants to wait. It doesn't get any loving simpler than: code:
Long story short: Use java.util.concurrent unless you're using Swing or JEE in which case consider the more specialized variants that they provide.
|
# ¿ Apr 7, 2010 04:57 |
|
Arguments to a method can be declared final in the implementation although it's not allowed in an abstract method. This simply indicates that the method will not change the values passed in even if pass by value semantics are enforced on all method calls normally. This is required if the values are to be accessible from within a local class defined inside the method. Otherwise it's merely a helpful indicator for the compiler when optimizing code and a way to ensure that the value isn't changed inadvertently.
|
# ¿ Apr 29, 2010 03:02 |
|
Yes. Streams that wrap other streams are supposed to close the underlying stream when they are closed unless there's a reason for them not to, in which case the calling code probably isn't supposed to close the underlying stream in the first place like the output stream for a zip file entry.
|
# ¿ Jun 28, 2010 03:14 |
|
If you call a program from the command line, normally you can include stuff beyond just the program name. For instance a program that copies a file would take the existing file and the name of the file you want to copy it to. In that case you would expect for the existing file name to be in args[0] and the new file name to be in args[1]. This is similar to how it's done in other languages like C, although in C the first parameter is always the name of the program being called (useful in some circumstances).
|
# ¿ Apr 4, 2011 03:29 |
|
Jabor posted:Is that actually the spec, or just an implementation detail? Spec. The JVM integer math operations act on 32-bit numbers or 64-bit numbers. Stuff gets sign extended when pushed on the stack and truncated when popped IIRC.
|
# ¿ Jul 21, 2011 14:02 |
|
Jabor posted:Right, so the spec is that the result is the same as if the math was performed on a 32-bit sign-extended version. Due to the rules of mathematics they act the same. Try it using 2 and 4 digit numbers and base 10 arithmetic rather than 8 bit or 32 bit numbers and you'll see that when you chop the first 2 digits off a 4 digit number it acts identically to the 2 digit number. Specs in general only define behavior, so as long as an implementation behaves identically, it's perfectly fine. You could write a stackless C implementation that uses garbage collected activation records instead and it'd be perfectly legal, if a bit perverse. Most RISC processors just have one add instruction since it acts identically for all widths both as 2's complement as well as unsigned so they have to implement it in that manner. An IA-32 processor could treat a push of a byte onto the stack as loading into one of the byte-sized registers but you wouldn't be able to tell the difference.
|
# ¿ Jul 22, 2011 02:24 |
|
Scala's probably going to get more use out of the MethodHandles as a way to handle eta expansion without generating new anonymous classes. That's also the direction that Java 8 looks to be going with lambda definitions with some way to make a single MethodHandle with a given MethodType impersonate an interface or abstract class with a single abstract method of the same MethodType. Also, the escape analysis being enabled by default in Java 7 (and I think Java 1.6u23 and up as well) will probably have a bigger impact on Scala programs. Being able to stack allocate millions of tiny objects with short lifespans turns them from cheap into effectively free. This has caused some (highly contrived) microbenchmarks to run several times faster in tests but the average Scala program's still going to benefit somewhat since it does allocate a lot of the aforementioned tiny objects with short lifespans.
|
# ¿ Aug 1, 2011 13:51 |
|
|
# ¿ May 12, 2024 08:39 |
|
To take a somewhat fundamentalist position, the only place that you should really be referring to the implementation class outside of its implementation should be the constructor. If that's the case, then the interface shouldn't have its name mangled.
|
# ¿ Sep 4, 2011 04:40 |