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
Jabor
Jul 16, 2010

#1 Loser at SpaceChem
The way the UI thread works is this:

1. Have any events happened?
2. If yes, run the associated event handler
3. Have any events happened?

One of those events is the window-drawing event - when something on the window changes and the whole thing needs to be redrawn, the redraw is processed much like any other event.

If your event handling code locks itself up (say but doing a Thread.sleep()), then the redrawing code won't ever get to run until your event handler finishes up.

You basically need to be using the timer class - make sure you're using the javax.swing.Timer version, as you can run into threading issues with java.util.Timer.

Adbot
ADBOT LOVES YOU

Jabor
Jul 16, 2010

#1 Loser at SpaceChem
You can only really write out characters, and sequences of characters.

Thankfully, there is a built-in way to convert any arbitrary object to a sequence of characters - the toString method.

Most standard-library types that you'd want to print have a reasonable implementation of it already, if you want to print out a class that you've defined then you'll need to override the default with something that's reasonable for your class.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem

epswing posted:

I don't obsessively null-check every possible reference, but array[number].method() scares me. Am I really sure that (A) the array contains what I think it does,

You could, you know, check for null when you put something into the array. If you're inserting nulls into the array when they shouldn't be, your software is broken and you should crash instead of loving up important data by pretending everything's just dandy. Once your software is in a hosed-up state, crashing is better than most of the alternatives.

And if nulls are valid in the array, you're probably doing something wrong. If they're used to indicate an invalid object at that position, then you're probably better off with the null-object pattern, because then you have the option of attaching additional information later on about why it's invalid without having to rewrite everything that deals with that data.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem

Clank posted:

When should SwingUtilities.invokeLater ( Runnable ) be used?

When you're doing a bunch of processing on a non-GUI thread (which is what you should be doing) and that processing thread needs to update the UI.

For example, you could use it to update the progress bar of a long-running task, or change the status line to indicate what the task is currently doing or something.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem

epswing posted:

Who says I put anything into the array? Maybe I was passed the array from some part of the program that some other guy in my company wrote. Or from some dll written by some other guy in some other company. What world do you live in where you magically know everything about the data you're receiving?

Ah yes, that mythical, nonexistant world where documentation exists.

If someone's calling into your code, and they're doing crazy stuff that violates the spec you've provided, you should throw a relevant exception (like, say, a NullPointerException if something's null that shouldn't be). Doing otherwise doesn't actually solve anything - trying to make sense of invalid data and giving a meaningless result is worse than crashing.

If you're calling into someone else's code, and it's breaking spec, then again, you should be crashing. If trusted code is screwing up like that, you have no idea what other poo poo is hosed up, you have no idea what other data is sane, and you have no idea what data you're going to irreversibly corrupt if you try and carry on.

The only time you don't want to do that is if it's an "untrusted" library you're calling into (such as a plugin), in which case it should be sandboxed appropriately, and anything it gives you should be validated well before you attempt to use it, so again, you shouldn't be trying to hide or compensate for invalid data at that point.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem
It seems like you can only have one "template" in a particular category at a time. That being the case, I honestly don't think lumping them all together is actually a good idea. It smacks of over-engineering.

Both processor threads and pigeons can die, but that doesn't mean they need a common base class.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem
I think part of the issue is you're looking at hue. Don't. It's irrelevant. Distinguishing shape is much faster and easier, and gives you all the information you need. Greyscale, threshold, perhaps some denoising, and then it's trivial for any image classification algorithm.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem

Nippashish posted:

I disagree with Jabor's suggestion to ignore hue. Ignoring color is pretty common when trying to recognize objects in images but, it's not because color doesn't have any information. In photographs (which is what people usually care about) color is very hard to deal with because different lighting conditions/camera properties/phases of the moon/etc can cause the color values for pixels to vary dramatically. It turns out that perceptually similar colors and optically similar colors don't really match up well and it is very difficult to design algorithms that account for the perceptual quirks of human vision.

That said, you are not dealing with photographs. The colors in your situation are very controlled; presumably Bejeweled is not using a perceptually similar but optically different shade of blue each time it shows a blue gem. I would handle color here by treating each channel separately and combining the results. You could, for example, do NCC as I described above on each channel and sum the results to get a final score for each template.

Even in the case of Bejeweled, there's still quite a bit of chroma noise. Here's an example screenshot from what I gather to be a version with fewer fancy effects:



I'd expect the flashes in particular to be a big hassle if you're trying to work off chroma.

And after a basic greyscale+threshold:



The octagons and circles are a little ambiguous (and you'd probably want to fall back to hue for those), but everything else is trivially distinguishable. Fair enough, NCC on the original image would probably distinguish gems just fine. But that's three times the work for a similar result.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem
You basically want to call repaint 24 times at 50-millisecond intervals, right?

Now, the first rule of UI programming is that event handlers should do what the need to and then return quickly - if you have an event handler that takes a second or so to run, then your application isn't processing any more events for that second, your UI isn't being redrawn, basically the user sees your application lock up and become nonresponsive. I would guess that's what's happening here - repaint is being called 24 times, but you only see the results of the last one because the UI doesn't get updated in between.

So Thread.sleep() in an action listener is not a good idea. Instead, to call something at specified intervals, you want to use a timer.

code:
//setup code (``timer'' is a field somewhere)
ActionListener fuckWhyDoesntJavaHaveAnonymousFunctions = 
    new ActionListener() {
  int i = 0;
  public void actionPerformed(ActionEvent e) {
    if(++i < 24)
      frame.repaint();
    else
      timer.stop();
  }
}
timer = new Timer(50, fWDJHAF);

//button action listener
public void actionPerformed(ActionEvent e) {
  timer.start();
}

Jabor
Jul 16, 2010

#1 Loser at SpaceChem

Red_Fred posted:

Your guess was spot on that the elevator can only hold 4 people so the array is for 4 variables. However some of them will be null because it's up to the input as to what people are on what floor and if they need picking up etc. Should my loop be <= instead of < ?

Walk through the loop by hand. What happens when `a' is:

0?
1?
2?
3?

Pay particular attention to the last one.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem
fireTableDataChanged doesn't immediately update the table. It just says to the UI thread "Hey something happened".

When the UI thread gets back to processing its event loop, it will call any associated event handlers, one of which will be the table redoing its layout.

If this code is running on the UI thread, I'm honestly surprised that it was working even some of the time. OTOH, if it was on a different thread to the main event loop, then that sort of thing is expected.

Swing doesn't seem to have a "Call me whenever you redo your layout" listener, which would be ideal for this sort of thing, so the idea of firing another event to have the scroll-to-bottom happen after the layout is redone is probably the best alternative.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem

Internet Janitor posted:

If you call invalidate() on the appropriate components before you get their dimensions, shouldn't it force Swing to recalculate the layout?

invalidate is similar to that mentioned above in that it just says "hey you need to redo your layout before the next time you draw yourself".

You could possibly do it synchronously with doLayout(), though.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem

PlesantDilemma posted:

Thanks for the info. However, while I was googling JAR's and setting up classpaths, my classmate told me that I had to upload the class$x's that NetBeans generates. I had originally just uploaded Applet.class from the build folder. NetBeans also had Applet.class$1, Applet.class$2, Applet.class$3, Applet.class$4, Applet.class$5 in the build folder. I had assumed these were intermediary files that weren't needed but when I uploaded them to the same folder as my Applet.class it was able to work correctly. I'm gonna have to do some more googling because my professor is useless.

Java has this silly thing where each compiled class has to be in one file. Even if it's an inner class of something else.

So if you end up making a lot of anonymous classes (which you probably are doing if you're doing anything with events because ... Java), you're going to end up with a lot of extra .class files.

Generally though, if you're doing anything with your app other than running it on your own machine for testing, you want to get your IDE to package it all up in a .jar file instead of mucking about with the class files yourself.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem

Evilreaver posted:

I'm trying to use Greasemonkey to pull values out of a standard HTML table but am having no luck (probably because it's been too long since I've coded last).

So you have something like:

code:
<tr>
  <td>value1</td>
  <td>value2</td>
  ...
</tr>
and want to pull out value1, value2, etc,?

You can use the innerHTML property to get the entire contents (raw markup and all), or use nodeValue to get more structured information.

The important thing about nodeValue is that it doesn't do anything with the contents of a node - it only returns the value of the node itself (I figure this is what you mean by "unhelpful stuff"). You want to look at the elements in the childNodes collection if you want to get at the stuff inside it.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem

Evilreaver posted:

Value1 etc are plain text. If I understand what you're saying, I need something like tableIndex.getChildNodes.??? I don't know what the node structure looks like and the API I'm looking at isn't helpful in that regard. How could I even explore that?

This is why I'm a bad coder, I always get caught on this stupid poo poo. :( The meat of the program is easy, it's the interfaces I cannot work.

e: Oh hang on, innerHTML is leading me somewhere

When you use getElementsByTagName, you get a collection of element nodes. When you have an element node containing text, for example:

code:
<td><p>Hello World</p></td>
what it looks like as far as the API goes is thus:

code:
{stuff}
 |-<td> element node
    |-<p> element node
       |-"Hello World" text node
If you use nodeValue on an element node, you basically get back the type of the node - "td" or "p" or whatever. You need to use nodeValue on the text node inside that if you want to get the textual content.

Out of interest, what documentation are you looking at to figure out this stuff? The DOM is something which has both lots of good documentation and lots of especially crappy stuff, and it really helps to be looking at the right thing.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem
I'd recommend looking at the w3schools documentation on the DOM.Don't do this.

Are you sure it's returning the string "300" and not, say "'300'"?

Jabor fucked around with this message at 06:16 on Jun 2, 2011

Jabor
Jul 16, 2010

#1 Loser at SpaceChem
Is there a reason you need to do this drip-feeding instead of, say,

code:
Future<Object> f = p.parseAsync(networkStream);
//do some other stuff
Object o = f.get();
//alternatively hand it off to another thread to do

Jabor
Jul 16, 2010

#1 Loser at SpaceChem

Cubiks posted:

My end goal is to have a single server, many client setup, where creating a thread on the server for each client just wouldn't scale.

This is a solved problem. Deal in work items, not threads, and use callbacks instead of synchronous IO.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem

Aleksei Vasiliev posted:

Since NIO was just brought up and I'm an idiot, is there anything wrong with this code? It reads a file into memory.
code:
It works, I'm just paranoid I'm doing something wrong and it'll randomly fail or leak resources.

It should work fine. Though honestly if you're just looking to slurp the whole file into memory there are easier ways:

code:
RandomAccessFile f = new RandomAccessFile(world, "r");
byte[] b = new byte[world.length()];
f.readFully(b);
f.close();
return ByteBuffer.wrap(b);

Jabor
Jul 16, 2010

#1 Loser at SpaceChem

chippy posted:

Is there a quick simple way of doing modular subtraction in Java?

For example, if I want an int to go from 0..9 and then "wrap" back to 0 when incremented from 9 it's easy to do with ++i % 10. Is there a quick way of doing it if I want to go the other way, i.e. when i is 0 and is decremented, it goes back to 9?

Obviously there are easy ways of doing it with if statements and the like but I'm looking for a one statement/line solution, more for my own interest than anything.

I'm sure the answer is blindingly obvious but I'm having trouble figuring it out.

The conditional operator makes if-else logic basically a one-liner:

code:
i = (i > 0) ? i - 1 : 9; 
Alternatively you could use the modulo mechanism by just reversing the direction of the field a couple of times:

code:
i = 9 - (((9 - i) + 1) % 10);

Jabor
Jul 16, 2010

#1 Loser at SpaceChem

Mustach posted:

Why would you want an instance of a superclass to be equivalent to an instance of a subclass? A canonical implementation of equals() will always return false for such a comparison.

Yes, you would get told "yep, these two objects aren't equal" at runtime when you compared them.

As opposed to you getting a compile error because you're passing a Foo to a method that only accepts a FooImpl.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem
Part of it is the diagonal inheritance issue with interfaces.

Suppose I have two collections, one containing IFoos and the other containing IBars. Part of the contract of my class is that a given object should only be in one of those sets, even if it implements both interfaces.

Should I go around checking types and casting things myself? Or should we just allow the collection methods to take an Object and if it's not present ... act like it's not present?

What does having looser type constraints on those methods actually cost?

Jabor
Jul 16, 2010

#1 Loser at SpaceChem

Aleksei Vasiliev posted:

...

Probably unrelated, but instead of adding an array of callables one-by-one to a CompletionService, you can just use ExecutorService.invokeAll().

Ulio posted:

So I am back again asking for some direction, I need to write an app, where the user inputs a 5 digit number, the system then prints the number with three spaces between each number. So if the user enters 12345 we would see 1 2 3 4 5
It says I should use the division and operand but so far I haven't got a clue how to make this happen.

There are two ways of doing this:

1. The way the assignment says you should do it.
2. The non-stupid way.

The assignment is asking you to:

1. Parse the user input into an integer
2. Use modulo and division to get the individual digits
3. Print them out separated by spaces

I assume you've got part 1 working.

Part 2 is asking you to convert an integer into a string in a particular base. There are a bunch of patterns for doing this, but the basic idea is:

The rightmost digit is n % b
The next digit to the left is (n / b) % b
The digit to the left of that is (n / b^2) % b
And so on....

The non-stupid way is of course to get the digits straight from the string the user provides, instead of turning it into an integer and back again.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem

Ulio posted:

I did this for each possibility so it was lots of copying and pasting. I just want to know if there is another way(pretty sure there is), but not something too advanced. Thanks.

Suppose that, instead of knowing ahead of time how many numbers you were comparing, you were just given a bunch of them in an array and had to pick out the largest and the smallest. How would you go about doing that?

Jabor
Jul 16, 2010

#1 Loser at SpaceChem

I am in posted:

Java does a widening conversion to ints when operating on shorts and under the hood the JVM handles primitive values as ints anyway, so there's no advantage.

Is that actually the spec, or just an implementation detail?

Jabor
Jul 16, 2010

#1 Loser at SpaceChem

1337JiveTurkey posted:

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.

Right, so the spec is that the result is the same as if the math was performed on a 32-bit sign-extended version.

But there's no requirement that a conforming implementation actually do this, is there?

Jabor
Jul 16, 2010

#1 Loser at SpaceChem
The fun part of autoboxing is that it caches "frequently-used" values, which lets you do something like this:

code:
Field iv = Integer.getClass().getDeclaredField("value");
iv.setAccessible(true);
iv.setInt(Integer.valueOf(1), 500);
Which is guaranteed to piss off anyone else who has to maintain your code.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem
Add a preprocessor to your compilation chain and use macros.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem

Brain Candy posted:

Java 7 fixed some bugs

The also introduced some bugs, if your code has loops in it.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem

Blacknose posted:

Already tried that and it returns a string, I need to end up with a double, same as when I started. I'm not actually 100% convinced it's possible.

A double is just a number. "160.0" and "160.00" are both strings, that represent a number.

There is no such thing as a double that has a particular formatting. It's just a double. A collection of bits that represent a number. You decide when you print it out how you actually want to display it.

You are asking a question that has no answer - not because what you want to do is impossible, but because it's meaningless.

What are you actually trying to achieve?

Jabor
Jul 16, 2010

#1 Loser at SpaceChem
If it's going into Excel, why isn't a string suitable?

As far as I'm aware Excel treats a cell containing the string "160.00" pretty much the same as one containing the number 160 when it comes to calculations?

Jabor
Jul 16, 2010

#1 Loser at SpaceChem
The fact that it works if you poll the device more often suggests that the connection is being closed due to not having any traffic.

How exactly are you communicating with the device?

Jabor
Jul 16, 2010

#1 Loser at SpaceChem

Hidden Under a Hat posted:

I'll have to be dig around in the serial hub configuration to see if there is an actual setting that causes port closure due to lack of activity, but regardless if what you mentioned is the problem, would setting setKeepAlive(true) on the socket be sufficient to prevent closure?

"Try it and see" would be my recommendation. It does seem like that is the sort of problem which setKeepAlive(true) would fix...

Jabor
Jul 16, 2010

#1 Loser at SpaceChem
In order to solve this problem, you're going to have to do one of two things:

1. Have a line of code somewhere saying that there is a property called <whatever>, or

2. Forgo compile-time checking, and have some way to map strings to messages (and use that every time you access a message).

If you do go for (1), then you don't have to do that in every file - in fact, you could automatically generate a file that looks like so:

code:
//boilerplate...
public class ErrorStrings {
    public static final string COMMS_ERROR;
    //etc...

    static {
        Properties p = new Properties();
        p.load(/*blah*/);
        COMMS_ERROR = p.getProperty("COMMS_ERROR");
        //etc...
    }
}
And then import static that into anything that uses those constants.

Or don't do a static import, and just access stuff as ErrorStrings.COMMS_ERROR or whatever.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem

brosmike posted:

code:
        reallyA.equals(b); // Still true - great!
        b.equals(reallyA); // Nope. poo poo.
        reallyA.equals(reallyA); // Double poo poo

I get false, false, true.

Overload resolution is done based on the static type of the expression - since Object doesn't have an equals(Butt) method, equals(Object) gets picked.

The fact that you're not actually overriding the equals method is begging for trouble, but it's not quite as bad as you're presenting.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem
I use the "I" prefix for interfaces, which leaves the base word free for an abstract class if necessary. It's better than calling your abstract class a FooAdapter or something like that.

Since I haven't seen an IDE that syntax-colours interfaces differently from classes, it's nice to be able to distinguish them at a glance.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem

Aleksei Vasiliev posted:

Why do you need interfaces to be different colors?

The same reason you want keywords to be coloured differently to class names.

That is; you don't. But it's a nice-to-have.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem

Hidden Under a Hat posted:

The first involves passing an invisible JButton through each object instantiation. The JTabbedPane has the action listener for the button that invokes a method to implement a change, and as each subsequent JPanel/JDialog is instatiated, the JButton is passed to it in the constructor. In the final component, when the actual physical button is pressed, I simply invole the doClick() method of the invisible JButton.

Why does this need to be a full JButton again?

Fundamentally, you're basically trying to attach an actionListener from the JTabbedPane to a deeply-nested JButton - so wouldn't it make more sense to just pass down the actionListener and have the bottom JPanel attach it for you?

Now, whether that's the best design or not is up for debate. There's basically two ways of doing this:

1. The JTabbedPane manages everywhere that could change its title. In this case, doing it as above makes sense.
2. The JTabbedPane exposes a means to change its title, and doesn't care about it otherwise.

In the second case, you probably want each JPanel to grab the "change the title" method and expose it to its direct child, so you're not overdependent on the exact level-of-nesting that you have going on.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem

Sab669 posted:

Why is equals() better than ==? I'm a huge noob at all of this... and in related news! The reason why I came to this thread.

Unlike C#, Java doesn't support overloading of operators - while in C# you might overload the == operator on a class to mean something sensible for that class, in Java the == operator has a fixed meaning across everything.

When using == on a primitive value type, it checks if they are the same value, as we expect. But when using it on a reference type (i.e. anything that's actually a class), the == operator checks for reference equality - that is, whether both parameters refer to the exact same thing. So if you have two strings, they might both say "bob", but if they're two different objects at two different places in memory, == will say that they're different.

Sometimes you want to check reference equality - but most of the time it's value equality that you're interested in, so you should be using equals().


Ensign Expendable posted:

The difference between .equals() and == is that the first compares the contents of the class, whereas the second compares their references. "a".equals("a") will return true, but "a"=="a" will return false, since those are two different String objects.

This might not be the best example - try the following:

code:
public static void main (String[] args) throws java.lang.Exception
{
        System.out.printf("equals(): %b\n", "a".equals("a"));
        System.out.printf("==: %b\n", "a" == "a");
}
The java compiler performs interning on string literals, which means that no matter how many times you write "a" in your code, only one string actually gets emitted (and so, of course, reference equality 'works').

This makes it even more annoying to debug issues caused by == if you don't know what's going on - your program works fine with hardcoded inputs, but as soon as you switch it to taking input from the user, it breaks.

Jabor fucked around with this message at 01:13 on Oct 31, 2011

Adbot
ADBOT LOVES YOU

Jabor
Jul 16, 2010

#1 Loser at SpaceChem
It actually looks fairly similar to Photoshop's "Overlay" mode.

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