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
Malloc Voidstar
May 7, 2007

Fuck the cowboys. Unf. Fuck em hard.
Why does Java allow $ and _ as valid variable names? Apparently it's legacy, and I'm wondering what it was used for. (edit: Apparently only $ is legacy)

Somewhat relevant to the card talk, here's a Fisher-Yates shuffle:
code:
void $_() {
	for (int ___ = $.size() - 1; ___ > 0; ___--) {
		final int __ = _.nextInt(___ + 1);
		$$(___, __);
	}
}
// ArrayList<Card> named $, $$() swaps cards at the specified positions, _ is a Random()
Java (well, Sun/Oracle) seems to hold on to legacy support too hard. Like how it can't read UTF-8 text if there's a byte-order mark because it would break old programs: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4508058 (which made me very confused for awhile, since Win7 really likes UTF8+BOM)

Malloc Voidstar fucked around with this message at 12:23 on Dec 10, 2010

Adbot
ADBOT LOVES YOU

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.
Why shouldn't they be allowed? The language shouldn't mandate what is and isn't a good identifier; in general, it's an impossible decision for a compiler to make. I think that the above is negligibly less understandable than
code:
void aa() {
	for (int bbb = a.size() - 1; bbb > 0; bbb--) {
		final int qq = z.nextInt(bbb + 1);
		ff(bbb, qq);
	}
}

Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."
AV: There are a ton of valid unicode characters, too. I know there's at least one valid character that is invisible and a number of characters (like capital Alpha) that share glyphs with normal Latin characters. Unicode is a massive bag of worms no matter how you slice it. Did you know unicode escapes (\uXXXX) are processed before tokenization?

Max Facetime
Apr 18, 2009

I can see why they've chosen not to fix it. A Unicode Character 'ZERO WIDTH NO-BREAK SPACE' (U+FEFF) written in UTF8 encoding should be able to be read back using the inverse code, but that's not possible:

Unicode.org posted:

Q: I am using a protocol that has BOM at the start of text. How do I represent an initial ZWNBSP?

A: Use U+2060 WORD JOINER instead.

The root cause is that Unicode uses bytes 0000FEFF, FFFE0000, FEFF, FFFE, EFBBBF as a byte-order mark when in actuality they are magic numbers that specify the format of the contents that follows:

UTF-32 (variant A) = 0000FEFF + UTF-32BE
UTF-32 (variant B) = FFFE0000 + UTF-32LE
UTF-16 (variant A) = FEFF + UTF-16BE
UTF-16 (variant B) = FFFE + UTF-16LE

But for UTF8, the magic number is optional, worse yet it's a valid byte sequence in the contents that follows.

The problem is in the Unicode Standard. In Java it could be fixed by adding a new Charset UTF-8B that writes the BOM to start and reads a BOM from start if one is present.

Malloc Voidstar
May 7, 2007

Fuck the cowboys. Unf. Fuck em hard.

Internet Janitor posted:

Did you know unicode escapes (\uXXXX) are processed before tokenization?
Yes, when I tried to use the Unicode escape codes for \r\n. :mad:
Man was I confused over that.

Also I didn't know Unicode characters are valid identifiers, which is fun.


But why does Oracle specifically point out never ever to use $? (Here, Naming section)

edit:

I am in posted:

But for UTF8, the magic number is optional, worse yet it's a valid byte sequence in the contents that follows.

The problem is in the Unicode Standard.
ZWNBSP was deprecated in 2002. U+FEFF, mid-stream, is supposed to be treated as a zero-width non-breaking space because it does nothing.

Malloc Voidstar fucked around with this message at 16:58 on Dec 10, 2010

Parantumaton
Jan 29, 2009


The OnLy ThInG
i LoVe MoRe
ThAn ChUgGiNg SeMeN
iS gEtTiNg PaId To Be A
sOcIaL MeDiA sHiLl
FoR mIcRoSoFt
AnD nOkIa

Aleksei Vasiliev posted:

Why does Java allow $ and _ as valid variable names?

How else could you write something like this?

code:
interface function<T> {
    void _(T t);
}

public class JHorror<T> {
    private T t;
    public JHorror(T t) { this.t = t; }
    public void _(function<T> function) { function._(t); }
}

public class IWantToBeJavaScript<T> {
    public static void main(String[] args) {
        $("Hello")._(new function<String>() {
            public void _(String t) {
                System.out.println(t + ", have a horror.");
            }
        });
    }
	
    public static <T> JHorror<T> $(T t) {
        return new JHorror<T>(t);
    }
}

Parantumaton fucked around with this message at 16:52 on Dec 10, 2010

Max Facetime
Apr 18, 2009

Aleksei Vasiliev posted:

ZWNBSP was deprecated in 2002. U+FEFF, mid-stream, is supposed to be treated as a zero-width non-breaking space because it does nothing.

As long as it is supposed to be treated in any way other than as an invalid byte sequence the problem remains.

But eight years should be long enough time to finally disallow that codepoint :)

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

Aleksei Vasiliev posted:

But why does Oracle specifically point out never ever to use $? (Here, Naming section)


Inner classes (and closures in other languages) use $ to denote their "inner-classness" when javac builds their class files. It's probably just so you never run into a situation where an inner class name collides with a variable you made.

Necc0
Jun 30, 2005

by exmarx
Broken Cake

Necc0 posted:

for the life of me I can't figure out how graphics2D is supposed to work. the two relevant classes:

http://pastebin.com/vMsCXtcC

and:

http://pastebin.com/PjzNe2hD

I've tried setting jPanel1 equal to the draw object, then running the draw object. I've tried passing display.jPanel1 into the drawImage functions, and now I've tried the current iteration. No matter what I do I get nothing to the screen.

I know the images are in the right place because the older iteration of this program was just using the graphics library to draw, and while it worked it looked terrible and took forever to refresh.


fwiw The paintComponent method isn't being called at all if that helps any. Anyone have any ideas?

Paolomania
Apr 26, 2006

TRex EaterofCars posted:

Inner classes (and closures in other languages) use $ to denote their "inner-classness" when javac builds their class files. It's probably just so you never run into a situation where an inner class name collides with a variable you made.

They wouldn't collide. Inner classes look like FooClass$BadName (inner class BadName) as opposed to FooClass.$BadName (class member $BadName).

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

Paolomania posted:

They wouldn't collide. Inner classes look like FooClass$BadName (inner class BadName) as opposed to FooClass.$BadName (class member $BadName).
Well you could always do int FooClass$BadName = 3; or something

...but it doesn't matter, I tried to make it collide and javac figured it out fine.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
Is there any way that I can use the batik rasterizer in a webapp without having to execute a shell command or write to the local file system?

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

fletcher posted:

Is there any way that I can use the batik rasterizer in a webapp without having to execute a shell command or write to the local file system?

You can get the source... just dick around with the methods that handle the argument list and you should be able to figure out how to call it from within your program.

Malloc Voidstar
May 7, 2007

Fuck the cowboys. Unf. Fuck em hard.

fletcher posted:

Is there any way that I can use the batik rasterizer in a webapp without having to execute a shell command or write to the local file system?
http://xmlgraphics.apache.org/batik/using/transcoder.html#createImage
Though using PNGTranscoder instead of JPEGTranscoder, obviously. And don't use a FileOutputStream, keep it in memeory.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Aleksei Vasiliev posted:

http://xmlgraphics.apache.org/batik/using/transcoder.html#createImage
Though using PNGTranscoder instead of JPEGTranscoder, obviously. And don't use a FileOutputStream, keep it in memeory.

Sweet! Thank you!

Necc0
Jun 30, 2005

by exmarx
Broken Cake

Necc0 posted:

fwiw The paintComponent method isn't being called at all if that helps any. Anyone have any ideas?

anyone? I still haven't figured this out and I'm ready to scream.

ShardPhoenix
Jun 15, 2001

Pickle: Inspected.

Necc0 posted:

anyone? I still haven't figured this out and I'm ready to scream.
Your code is pretty complicated, try doing something simpler and see if you can get drawing working at all. Also, I don't know why you have separate Graphics2d objects for each image (I'm no expert on Java graphics but when I've done it, I've had one graphics object that I used to draw everything).

ShardPhoenix fucked around with this message at 06:13 on Dec 12, 2010

Surface
May 5, 2007
<3 boomstick

ShardPhoenix posted:

Your code is pretty complicated, try doing something simpler and see if you can get drawing working at all. Also, I don't know why you have separate Graphics2d objects for each image (I'm no expect on Java graphics but when I've done it, I've had one graphics object that I used to draw everything).

I create separate java graphics objects per layer of rendering- specifically its useful if you need to apply different AffineTransforms to the different drawing layers in a game.

Stealthgerbil
Dec 16, 2004


I cant figure out for the life of me what this swing component is named. Its pretty much a JComboBox but instead of dropping down, it has an up/down arrow button on the right side. It is used through going through a large amount of data or selecting numbers or anything that is in an order.

RichardA
Sep 1, 2006
.
Dinosaur Gum

Stealthgerbil posted:

I cant figure out for the life of me what this swing component is named. Its pretty much a JComboBox but instead of dropping down, it has an up/down arrow button on the right side. It is used through going through a large amount of data or selecting numbers or anything that is in an order.

JSpinner

Malloc Voidstar
May 7, 2007

Fuck the cowboys. Unf. Fuck em hard.
Is there a more-proper way to do what I'm doing here?

code:
Map<String, Integer> country = new HashMap<String, Integer>();

// add entries to map

ArrayList<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>(country.entrySet());
Collections.sort(list, new ValueComparator()); //Comparator that sorts based on entry's value
for (Entry<String, Integer> e : list)
	System.out.println(e.getKey() + ", " + e.getValue());
I'm sorting a list of countries based on a value, so the output is ex:

quote:

Germany, 421
United States, 351
France, 185

It works fine, but I'm wondering if I'm going about this in completely the wrong way.

the onion wizard
Apr 14, 2004

SortedMap perhaps?

edit: oh, sorting on value, nevermind.

Max Facetime
Apr 18, 2009

Seems fine to me.

If you're going to hand the result list off to someone else you should consider creating your own immutable value class to hold the key-value pairs. The reasons are the Entries might hold a reference to the HashMap preventing it from being GC'd and your API shouldn't be leaking implementation details.

Stealthgerbil
Dec 16, 2004


I have been having some trouble setting up the JSpinner to retrieve data from my database. While it works perfectly, I have it so that each time the JSpinner changeevent happens, it connects to the database and executes an SQL statement. While it works for my purpose, I feel that connecting and doing a statement every time that the user changes the value in the JSpinner is terribly inefficient.

I cant figure out the proper way to just pass the entire resultset into the changeevent. Ideally I would have it initialize the connection when the panel loads, do the SQL statement and pass the resultset into the changevent. Then when the program is closed, it will close the connection with the database. I know that just doing one connection and one SQL statement is way better then doing it every time the user wants to retrieve the value.

At the moment, I have it check how many rows there are and then set the range for the JSpinner to that amount. Then when you click the JSpinner, it will retrieve the values from the row number.

Edit: I really just cant figure out how to pass the resultset into the changelistener :( I am totally stuck unless there is a better way :(

Stealthgerbil fucked around with this message at 00:32 on Dec 13, 2010

chippy
Aug 16, 2006

OK I DON'T GET IT
When the panel loads, execute your SQL query to get your list of values for the spinner, use getArray to get the column that has your values in from the ResultSet, and create a SpinnerListModel with the Array. Then when you create the JSpinner you pass it the SpinnerListModel.

e: If I've correctly understood what you're trying to do.

chippy fucked around with this message at 03:20 on Dec 13, 2010

Stealthgerbil
Dec 16, 2004


chippy posted:

When the panel loads, execute your SQL query to get your list of values for the spinner, use getArray to get the column that has your values in from the ResultSet, and create a SpinnerListModel with the Array. Then when you create the JSpinner you pass it the SpinnerListModel.

e: If I've correctly understood what you're trying to do.

This actually helped some however I figured it out. My current problem is pretty much increasing the range of the JSpinner and refreshing the ResultSet. Once I add in a value, it doesn't appear until I exit and reopen the program. Obviously that wont work. Is there a way just to like reload the panel or just increase the range of the JSpinner and retrieve another resultset?

Here is my code so far if it helps :)
http://pastebin.com/JnAr4C9R

edit: Well I just created a method in the frame class which deletes the tab and re-adds it and it works :P

I guess that's java for you...

Stealthgerbil fucked around with this message at 07:30 on Dec 13, 2010

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe
The real solution is to have your model live outside the scope of that method so that when you refresh the model the JSpinner updates automatically.

Necc0
Jun 30, 2005

by exmarx
Broken Cake

ShardPhoenix posted:

Your code is pretty complicated, try doing something simpler and see if you can get drawing working at all. Also, I don't know why you have separate Graphics2d objects for each image (I'm no expert on Java graphics but when I've done it, I've had one graphics object that I used to draw everything).

this:

Surface posted:

I create separate java graphics objects per layer of rendering- specifically its useful if you need to apply different AffineTransforms to the different drawing layers in a game.

Is exactly right. We're going to have the map, objects on the map, other players on the server, your own character, and a HUD, eventually. All of these can be pointing their own directions. This is really frustrating for me because usually this isn't an issue, and I've used Graphics2D in the past without any problems. For some reason *this time* I'm getting all sorts of hell.

Surface
May 5, 2007
<3 boomstick

Necc0 posted:

anyone? I still haven't figured this out and I'm ready to scream.

Have you created a thread that calls paint() (...or repaint()) on the JFrame (Display)? Swing only repaints components when needed unless you make it do otherwise.


On StackOverflow I answered a question about how to setup a tile based game, some of what is explained there might help you:

http://stackoverflow.com/questions/4189267/2d-java-game-moving-sprite-above-tiled-images/4189601#4189601


Here are some extracts:

Surface (instanceofTom) on StackOverflow posted:

A technique that works well for me is to separate the drawing logic of each layer into a separate class that implements the Painter interface (or a similar interface you define).
code:
public class TilePainter implements Painter
{

    @Override
    public void paint( Graphics2D g, Object thePanel, int width, int height )
    {
        //The tile painting code I posted above would go here
        //Note you may need to add a constructor to this class
        //that provides references to the needed resources
        //Eg: images/arrays/etc
        //Or provides a reference to a object where those resources can be accessed
    }

}
Then for the player painter:
code:
public class EntityPainter implements Painter
{

    @Override
    public void paint( Graphics2D g, Object thePanel, int width, int height )
    {
        g.drawImage(player.getImage(), player.getX(), player.getY(), null);
    }

}
If you are wondering why I am passing NULLs into the g.drawImage() function, its because for that overloaded function call the last parameter is an ImageObserver, which is something we do not need for this purpose.


Blah blah blah...

Now override the paint method in the JPanel:

code:
@Override
public void paint( Graphics g )
{
    int width = getWidth();
    int height = getHeight();
    //Loops through all the layers in the order they were added
    //And tells them to paint onto this panels graphic context
    for(Painter painter : layerPainters)
    {
        painter.paint(g,this,width,height);
    }
}

Stabbey_the_Clown
Sep 21, 2002

Are... are you quite sure you really want to say that?
Taco Defender
I've created a GUI in Java using the Swing containers, but I can't figure out how to connect the buttons on the GUI to the code. All the examples I've seen have the buttons being created in the code, or they only have one button which doesn't have a label (so I don't know how it can tell the difference between different buttons).

When using Swing, is it wrong to create the GUI first and the code later?

Necc0
Jun 30, 2005

by exmarx
Broken Cake

Surface posted:

Have you created a thread that calls paint() (...or repaint()) on the JFrame (Display)? Swing only repaints components when needed unless you make it do otherwise.

Are you saying the display class will have to call the draw's paintComponent with the paint call? Like, draw.repaint() or something like that? I thought that calling this.repaint inside it's own thread would handle that.

Blotto Skorzany
Nov 7, 2008

He's a PSoC, loose and runnin'
came the whisper from each lip
And he's here to do some business with
the bad ADC on his chip
bad ADC on his chiiiiip

Aleksei Vasiliev posted:

Somewhat relevant to the card talk, here's a Fisher-Yates shuffle:
code:
void $_() {
	for (int ___ = $.size() - 1; ___ > 0; ___--) {
		final int __ = _.nextInt(___ + 1);
		$$(___, __);
	}
}
// ArrayList<Card> named $, $$() swaps cards at the specified positions, _ is a Random()

Good to see you're all coming around to writing Perl :v:. Here's a Christmas present.
code:
#!/usr/bin/perl
$_='
         $q ="\                   47"; wh
        ile                           ($ ;=
      $z                +=              .5 ){
    %c=           $r=0;$/ ="";whi         le(2
   0+          $z>($;+=.05)){$c{int$       _+ 2
  6+         2*($              r+= .0       2) *
 s          in$                   ;}{1       -$_
+1         0+           int        $r*c       o s
$         ;}         =1for(0.       .1)        }$
t        =r         ever se;$        /.        =`
c        le        ar     `.         "         #!
/        usr       /bi             n/         pe
rl       \n\       $_ =$q        \n"          ;
fo        r$y        (1..20){$c{$_}          {
$ y       }? $         /.=chop$t            :
 ($/        . ="                          \4
 0")         for(0.                    .53)          ;
   $/.        ="\n"}pri            nt"$/$          q;
   s; ".         chr(9 2)."s;;g;eval\n           "}

';s;\s;;g;eval
no it won't format your hard drive or anything

Surface
May 5, 2007
<3 boomstick

Necc0 posted:

Are you saying the display class will have to call the draw's paintComponent with the paint call? Like, draw.repaint() or something like that? I thought that calling this.repaint inside it's own thread would handle that.

Didn't see you calling repaint() on line 121 (by pastebin), that is the type of call I was talking about.

Swing is setup so that (re)paint() calls should eventually call paintComponent, but you said it isn't being called? Just for grins try overriding the paint() method and placing the code from paintComponent() in there. You should figure out why paintComponent is not being called though.

Surface fucked around with this message at 02:30 on Dec 14, 2010

Necc0
Jun 30, 2005

by exmarx
Broken Cake
This is driving me nuts :mad:

Surface posted:

Swing is setup so that (re)paint() calls should eventually call paintComponent, but you said it isn't being called? Just for grins try overriding the paint() method and placing the code from paintComponent() in there. You should figure out why paintComponent is not being called though.

Correct. I know the thread is declared correctly as the println in the run() is printing, but the println in paintComponent() isn't. No clue. I'll try overriding the paint() method tomorrow to see what happens.

Necc0 fucked around with this message at 04:00 on Dec 14, 2010

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.

Otto Skorzeny posted:

Good to see you're all coming around to writing Perl :v:. Here's a Christmas present.
no it won't format your hard drive or anything
One of my favorites. Years ago, I saved it as "jah.pl", because "jah" is the noise I made the first time I ran it.

Jehde
Apr 21, 2010

How would one write a method that would translate a text file into a 2-dimensional character array with whitespace?

IE:
code:
X X X
 X X
X X X
Would turn into:
{{'X',' ','X',' ','X'}, {' ','X',' ','X',' '}, {'X',' ','X',' ','X'}}

lamentable dustman
Apr 13, 2007

🏆🏆🏆

I'd use a loop

epswing
Nov 4, 2003

Soiled Meat

osama bin diesel posted:

I'd use a loop

Can you be more specific? A for loop or a while loop?

Malloc Voidstar
May 7, 2007

Fuck the cowboys. Unf. Fuck em hard.

epswing posted:

A for loop or a while loop?
Yes

Adbot
ADBOT LOVES YOU

Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."
I'll bet he's going to need a variable as well. Maybe even two.

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