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
Hidden Under a Hat
May 21, 2003

Jabor posted:

Why does this need to be a full JButton again?



You're right it didn't need to be a jbutton. I changed it so it's just the actionlistener being passed which makes it cleaner.

Adbot
ADBOT LOVES YOU

gonadic io
Feb 16, 2011

>>=
Is there a "best practices" or conventions document for using swing?
The last thing I made, following the style of the sample code I was given had a big long
code:
public class MyApplet extends JApplet
     private JPanel usefulName
     private JPanel usefulName2
     ...

     public MyApplet () {
         populateUsefulName();
         populateUsefulName2();
     }

     private void populateUsefulName() {
         useulName = new JPanel();
         // other things
     }
}
Is this good or bad? Another style I saw was to have something like this instead of "populateUsefulName":
code:
private JPanel getUsefulName(){
     if (usefulName == null) {
          // populate usefulName
     }
     return usefulName;
}

gonadic io fucked around with this message at 14:43 on Sep 13, 2011

tripwire
Nov 19, 2004

        ghost flow

Internet Janitor posted:

I agree with everything in this post. In general the Java Collections API is one of the best designed corners of the standard library and well worth imitating.

Except for the glaring lack of compile-time immutable collections, and the violating liskov substitution principle thing.

Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."
The Liskov Substitution Principle is a questionable axiom. Taken to an extreme it would suggest you can't really use polymorphism.

Brain Candy
May 18, 2006

List is basically useless as an interface for solving real problems because I have no idea whether random access is going to require iterating through half the list.

HFX
Nov 29, 2004

Brain Candy posted:

List is basically useless as an interface for solving real problems because I have no idea whether random access is going to require iterating through half the list.

Who cares. The point of an interface is that you don't care about the underlying implementation, and if you do you go look up its instantiation / its behavior should be documented if it matters.

If it is really important because you are doing lots of lookups compared to insertions / traversals, then you define it as ArrayList because in this case you really do care about 0(1) element access.

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe

tripwire posted:

Except for the glaring lack of compile-time immutable collections, and the violating liskov substitution principle thing.

It's a shame really, because those would have been infinitely more useful than unmodifiableList and its ilk.

Thom Yorke raps
Nov 2, 2004


tripwire posted:

Except for the glaring lack of compile-time immutable collections, and the violating liskov substitution principle thing.

The fact that I have no idea whether a List can be modified is absurd; unsupported operations on interfaces are WTFTerrible. Oh, and one of the Collections has an improperly implemented .equals (pretty sure it is ArrayDeque).

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.
Speaking of pushing things to runtime, any interface that documents any of its members as "optional" can bite me.

Brain Candy
May 18, 2006

HFX posted:

Who cares. The point of an interface is that you don't care about the underlying implementation, and if you do you go look up its instantiation / its behavior should be documented if it matters.

If it is really important because you are doing lots of lookups compared to insertions / traversals, then you define it as ArrayList because in this case you really do care about 0(1) element access.

List (the interface) is is overly broad when I receive it from someone else. I shouldn't have to require an ArrayList, because my method will perform similarly on a any list with constant time element access... like the ones returned from Arrays.toList, or a Collections.unmodifiableList that wraps an ArrayList, let alone user defined ones.

Lysidas
Jul 26, 2002

John Diefenbaker is a madman who thinks he's John Diefenbaker.
Pillbug
I agree that it's asinine to have to do this, but you could declare things using the RandomAccess interface instead.

Brain Candy
May 18, 2006

RandomAccess is a marker interface. Hay, I love using instanceof (just like Collections classes are forced to!)

Malloc Voidstar
May 7, 2007

Fuck the cowboys. Unf. Fuck em hard.

Brain Candy posted:

RandomAccess is a marker interface. Hay, I love using instanceof (just like Collections classes are forced to!)
public <T extends List<?> & RandomAccess> void blah(final T obj) {/*dostuff*/}

e: of course this is a hacky solution since now anybody using this method can't call it with a List object, since List doesn't implement RandomAccess :v:

Max Facetime
Apr 18, 2009

Create your own internal copy: new ArrayList(unknownList). It's O(n).

Or change the method to require an array instead.

Malloc Voidstar
May 7, 2007

Fuck the cowboys. Unf. Fuck em hard.

I am in posted:

Create your own internal copy: new ArrayList(unknownList). It's O(n).
final List<Thing> work;
if (paramList instanceof RandomAccess)
    work = paramList;
else
    work = new ArrayList<Thing>(paramList);


Saves time when they aren't tossing you a LinkedList but it's gross. Which is part of what Brain Candy was annoyed at.

Max Facetime
Apr 18, 2009

Oh oh, I forgot the easiest one:

code:
/**
 * Note: this algorithm can perform slowly if the not given a List instance
 * that provides constant time random access to its elements.
 */

Brain Candy
May 18, 2006

The best comment should have occurred in when making Java 1.2 :

J. Bloch posted:


Re : LinkedList is NOT a List?!?!?

Look guys, just because LinkedList has List in the name doesn't mean it's a List. LinkedList is what we're calling a Queue. Yes, you can use comments to limit the problem with the runtime complexity, but you can't get around the problem of violating LSP; the ultimate caller of any function can be separated by several calls and may not know they are making an error.

Love,
J. Bloch

P.S. Deal with it.

I'm mad, mad about List.

mcw
Jul 28, 2005
Can you guys point to any code online somewhere that serves as a truly excellent example of unit and integration testing? Bonus points if it's testing JAX-RS and JPA.

The Atomic Man-Boy
Jul 23, 2007

Ill start off by saying that I'm new to Java and am a relatively novice programmer, and I'm trying to create an applet for my own education. It consist of this: I have 2 buttons, the create and delete button. When ever you click the create button, it draws a small circle on the screen in a random location (1 for each time you click) and when you click the delete button, it removes one from the screen. I plan to animate them and make them bounce off each other later, but for now just spawn and delete.

I was thinking of making an array of Objects derived from the oval class. And Im wondering what the basic logic of my program should be.

Tamba
Apr 5, 2010

This sounds like a basic game loop.

Here are some links:
http://fivedots.coe.psu.ac.th/~ad/jg/
http://www3.ntu.edu.sg/home/ehchua/programming/java/J8d_Game_Framework.html

Your program is basically running an infinite loop.
Each frame, you measure the time since the last frame, go through the list of all your objects, ask them to update their state (move themselves by their current speed multiplied with the time since the last update, do collision detection, react to keypresses, etc...). After all objects are updated with the current state, you clear the canvas, go through the list again and tell each object to draw itself at its current position.

When your create button is clicked you create a new Object and add it to the list, the remove button removes one object from the list.

chippy
Aug 16, 2006

OK I DON'T GET IT
Might also be worth looking into double buffering to avoid flickering. Basically instead of clearing the canvas and redrawing everything each time you have a separate image which you draw "off-screen" and then just set your canvas to display that.

http://download.oracle.com/javase/tutorial/extra/fullscreen/doublebuf.html

Hidden Under a Hat
May 21, 2003
I'm creating a Color object by getting the background color of the component using this code:

code:

Color bgc = Color.getColor(this.getColorModel().toString());

I know this works because I set the background color of a JTextField using that object and it sets it as the correct color:

code:

field.setBackground(bgc);

Now the part I don't understand. When I try to compare bgc to the background color of the JTextField (may or may not be bgc), I get a null pointer exception:

code:

if(bgc.equals(field.getBackground())){
      field.setText("True\n");
}
else{
      field.setText("False\n");
}

If I reverse the order of the argument, I get False returned:

code:

if(field.getBackground().equals(bgc)){
      field.setText("True\n");
}
else{
      field.setText("False\n");
}

If I try to reference bgc directly by using getRed()/getGreen()/getBlue()/toString()/etc I get NullPointerException, when the object should not be null since I'm able to correctly set the background color of the JTextField to that color. What's going on here?

EDIT: Like usual shortly after making this post I figured out a way to do it. Instead of using Color.getColor(this.getColorModel().toString()) I can just use getBackground() like I do for the JTextField.

Hidden Under a Hat fucked around with this message at 17:25 on Sep 23, 2011

Alterian
Jan 28, 2003

I don't know if I should post this in this thread or the game development thread, but I'm looking for a good book on java for video games. I'm working on a post bachelors certificate in computer programming and want to supplement my classes since they don't go into detail about programming for video games.

Malloc Voidstar
May 7, 2007

Fuck the cowboys. Unf. Fuck em hard.

Hidden Under a Hat posted:

If I try to reference bgc directly by using getRed()/getGreen()/getBlue()/toString()/etc I get NullPointerException, when the object should not be null since I'm able to correctly set the background color of the JTextField to that color. What's going on here?
Read the Javadocs.

setBackground
Parameters:
c - the color to become this component's color; if this parameter is null, then this component will inherit the background color of its parent

getColor
Finds a color in the system properties.

The argument is treated as the name of a system property to be obtained. The string value of this property is then interpreted as an integer which is then converted to a Color object.

If the specified property is not found or could not be parsed as an integer then null is returned.

MrTheDevious
May 7, 2006

Ahh nostalgia, you cruel bitch
I fully admit my company is backwoods, but if anyone here has experience with IBM WAS v6.1 as an app server + SpringMVC integration, please send me a PM. I've got a bet with another arch going that I can't integrate Spring's J2EE.jar requirements into our oldass WAS instance and I am beyond determined to win...

My J2EE.jar is beyond out of date and it appears j2ee.jar only comes from app server instances, so I can't seem to update it without totally nuking my RAD/WAS install and starting from the ground up. There's a bigass steak riding on this, so I need help!

*Edit - I actually think it's Hibernate causing the initial problem, but all Googling turns up is that I need to update j2ee.jar, which is fine and all, but I can't seem to get an updated version anywhere without grabbing the version WAS provides, which is NOT current enough. gently caress you, company who likes to use frameworks from 2004 and app servers not much more recent.

MrTheDevious fucked around with this message at 01:36 on Sep 27, 2011

Kilson
Jan 16, 2003

I EAT LITTLE CHILDREN FOR BREAKFAST !!11!!1!!!!111!

GodIsInTheTrees posted:

*Edit - I actually think it's Hibernate causing the initial problem, but all Googling turns up is that I need to update j2ee.jar, which is fine and all, but I can't seem to get an updated version anywhere without grabbing the version WAS provides, which is NOT current enough. gently caress you, company who likes to use frameworks from 2004 and app servers not much more recent.

Can't you just download a new Tomcat/Glassfish/Jboss/??? and get the j2ee.jar from that? There's a WAS v8 you can download a trial for - it probably contains some sort of j2ee jar as well. I don't know if any of these things will work, but it's worth a shot I guess.

GravyWPG
Sep 15, 2011

AAAAGH! BEEF GRAVY! IT'S BURNING MY FLESH! BUT IT'S SOOOO DELICIOUS!
I'm required to use some lovely program called Greenfoot for my computer science course. It isn't loving working.

I've installed the JDK version 7 prior to installing Greenfoot, and the installer tells me I don't have it. I carry on anyway and finish installing, and the program looks like this.



I ask the teachers about it and they tell me to install version 6. I do that, reinstall Greenfoot, reboot, and it STILL DOESN'T loving WORK. I'm missing assignments because of this loving poo poo.

Can anyone help me with this poo poo? My marks depend on it.

Thanks in advance.

epswing
Nov 4, 2003

Soiled Meat
What do you mean by "doesn't work"? What specifically isn't working? What are you expecting to see in that screenshot that you aren't seeing?

Scabies
Apr 1, 2007
Characterized by small pimples that itch.
e: nope.

Scabies fucked around with this message at 19:40 on Sep 24, 2012

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe

Scabies posted:

It might just not like JDK 7 for some reason, try reverting to six-point-whatever.

Did you not read his post? Also the Greenfoot website says it requires the Java 6 or Java 7 JDK.

edit for actual useful information: Uninstall anything called Java in your program files. Then download this JDK 6.27 and install it. Then download this Greenfoot Jar and you should be able to double click the file.

Janitor Prime fucked around with this message at 16:06 on Oct 4, 2011

ynef
Jun 12, 2002

GravyWPG posted:

I ask the teachers about it and they tell me to install version 6. I do that, reinstall Greenfoot, reboot, and it STILL DOESN'T loving WORK. I'm missing assignments because of this loving poo poo.

Can anyone help me with this poo poo? My marks depend on it.

Thanks in advance.
Since your grade depends on it, for now just get the portable version. It is self-contained and includes a JDK environment that the Greenfoot guys have tested and obviously ensure that works.

Choose the stand-alone version here:

http://www.greenfoot.org/download

Once that is done, try to fix things so you have your "real" Java environment up and running, but just take the packaged version first.

Suran37
Feb 28, 2009
Is there a way to make hasNextDouble(); end without having to pass a letter. I am trying to add the total with:

code:
		while(in.hasNextDouble()) {
			
			price = in.nextDouble();
			priceTotal = priceTotal + price;
			numOfPrices = numOfPrices + 1;
			
		}
Basically I input a line of double values, and after it totals them and all that it hangs at the while. I have to put a letter in, in order to pass the while loop and get the the next part of code that calculates average. Is there a way to get it to just go through the original line and not wait for a non-double value?

P.S. Incase you can't tell I'm in a freshman CS class.

Ensign Expendable
Nov 11, 2008

Lager beer is proof that god loves us
Pillbug
There isn't any way for the program to know the doubles ended unless you tell it, either by some terminator character (a null or something that fails the double parse and returns false on hasNextDouble()) or by knowing how many doubles there are and going through it a finite amount of times. Are you reading from a file or from keyboard input?

Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."
If you read the docs for Scanner you'll see that when the hasNext... methods are called they may block. Think about it- if you're sitting and watching somebody type, how do you know whether the next thing they're about to enter is a number until they hit a key?

If you want to parse doubles until you get a newline you might do something like this:
code:
import java.util.*;
class Reader {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		Scanner line = new Scanner(in.nextLine());
		double sum = 0;
		while(line.hasNextDouble()) {
			sum += line.nextDouble();
		}
		System.out.println(sum);
	}
}
Read in a whole line and build a new Scanner reading the resulting String. Since 'line' knows how long the String is, it knows when there aren't any tokens left. Make sense?

Sedro
Dec 31, 2008
Is there a way to make Netbeans or Maven raise errors/warnings for unchecked auto-unboxing? Currently this code doesn't raise a peep:
code:
Boolean b = null;
boolean b2 = b;

crazyfish
Sep 19, 2002

Sedro posted:

Is there a way to make Netbeans or Maven raise errors/warnings for unchecked auto-unboxing? Currently this code doesn't raise a peep:
code:
Boolean b = null;
boolean b2 = b;

Have you tried a static analysis tool like FindBugs?

Suran37
Feb 28, 2009

Internet Janitor posted:

If you read the docs for Scanner you'll see that when the hasNext... methods are called they may block. Think about it- if you're sitting and watching somebody type, how do you know whether the next thing they're about to enter is a number until they hit a key?

If you want to parse doubles until you get a newline you might do something like this:
code:
import java.util.*;
class Reader {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		Scanner line = new Scanner(in.nextLine());
		double sum = 0;
		while(line.hasNextDouble()) {
			sum += line.nextDouble();
		}
		System.out.println(sum);
	}
}
Read in a whole line and build a new Scanner reading the resulting String. Since 'line' knows how long the String is, it knows when there aren't any tokens left. Make sense?

Thanks for the help, I was having trouble figuring out how to get a line of doubles without making them into a string. I read somewhere that the console doesn't use and end line character, so I didn't think that would work.

Thanks again.

tripwire
Nov 19, 2004

        ghost flow

Sedro posted:

Is there a way to make Netbeans or Maven raise errors/warnings for unchecked auto-unboxing? Currently this code doesn't raise a peep:
code:
Boolean b = null;
boolean b2 = b;
Use intellij :D

Max Facetime
Apr 18, 2009

Or Eclipse!

But seriously, check if there's some setting for checking null pointer access in general, rather than boxing check.

Adbot
ADBOT LOVES YOU

Sedro
Dec 31, 2008
I get warnings for null pointers in general, just not the specific unboxing case. This problem arose because I switched code generators and the new one loves boxed types. Now I have a bunch of NullPointerExceptions waiting to happen with no way to find them.

I just switched IDEs after using eclipse for years because Netbeans' Maven + TomCat integration is so much better. I'm sure IntelliJ is great for standard Java development (I couldn't live without ReSharper).

crazyfish posted:

Have you tried a static analysis tool like FindBugs?
Thanks for this, although it doesn't solve my original problem.

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