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
Twitchy
May 27, 2005

Contract Otter posted:

I've now gone through two courses of Java-programming in my university and while I feel I know the basics of the syntax and object orientated programming, I'm a little frustrated that I don't really know how to program anything usable or sensible. Knowing how to program Game of Life or how to implement interfaces isn't exactly an adrenaline rush.

So do you have any advice where to go from here towards actual programming?

There's no "golden path" when it comes to programming. Just practice... alot, start small and work towards bigger projects, find out what works / is effective and read up on things you'd like to be able to do in your apps and apply them. Sort of generic advice, but programming is a pretty big subject that it's impossible to have "do this, then do that".

Adbot
ADBOT LOVES YOU

Twitchy
May 27, 2005

ShinAli posted:

I'm using a Combobox on a GUI I've created, and whenever I fill the combobox up, the little down arrow button on the right of it disappears. I do a repaint on the componenet but nothing. Then again, I really don't understand repaint that well as everytime I tried to use it, it never really works for me.

Have you tried calling revalidate on the panel it's in?

Twitchy
May 27, 2005

clayburn posted:

Haha it might be homework. I really just needed a point in the right direction like you gave, just some methods to look at. I've considered putting the words in some sort of array, I'm just worried about the efficiency of putting them there in the first place. I'll definitely check those methods out though, thanks.

You could tokenize the string like epswing said, or you can use the Matcher and Pattern classes (Regex) to do it for you, might aswell learn in now since it's incredibly useful. Basically what you want to search for is: 1 or more non-space characters, followed by an optional white space character, repeated 5 times.

http://java.sun.com/docs/books/tutorial/essential/regex/index.html is an ok place to learn Regex in Java.

I had a little shot at it and it's a pretty simple regular expression so once you know the basics it will be a piece of cake.

Twitchy
May 27, 2005

^^ Edit: Misunderstood you!

I think you've got it a little confused, primitives are passed by value, objects are passed by reference. Passing by value means the method has it's own copy, so even if the variable is changed during the method, it will not have an effect on the parameter that was passed in. Objects on the other hand, pass by reference, meaning any changes you make to them inside a method will change the same object you passed into the method.

When you set temp to null in that method, you are only saying that the variable no longer references the object. temp basically says "if you want to see what i contain, goto this location in memory", so when you it's set to null it just says "i don't refer to anything :(", but the location in memory still exists because there is another reference to it in the other method.

Jesus... I could never be a teacher.

Twitchy fucked around with this message at 22:11 on Apr 18, 2008

Twitchy
May 27, 2005

csammis posted:

Actually he's got it exactly right. The reference to the object is passed by value; you can modify the object, but not the reference to it.

I think it was me being a little confused about what he meant then heh. It's still passed by reference though really, saying it's passed by value just because it's reference is stored in a variable is more likely to confuse a new programmer than help them, that's all. I thought he thought (I thought that he thought that he thought) that because he set the variable to null but the other variable reference was fine that each method had it's own copy of the object / value.

Twitchy fucked around with this message at 22:12 on Apr 18, 2008

Twitchy
May 27, 2005

ShinAli posted:

Yeah I think I need to re-write it :psyduck:

Does "pass by reference" usually mean passing by value the copy of the reference? Or does real "passing by reference" mean that you can modify the original reference? If it's the former, then Objects passing by reference is actually correct and I'm just retarded :saddowns:

Yeah, passing by reference is assigning a variable to a location in memory, so setting it to null will not actually remove it (unless no other variables reference it, in which case it would be garbage collected).

You are right though, technically the reference IS passed by value, meaning you can set it too null and other references will be fine, but I think it can be a rather confusing thing to get, especially for new programmers where there needs to be a clear distinction between values (primitives) and objects.

Twitchy
May 27, 2005

Save the whales posted:

What do I put in the "getAggregateDescription" method of ExtendableThing to make it behave like this?

You might want to read up on downcasting objects, because at the moment the System.out.println statements will throw a ClassCastException. Maybe someone else who has a way with words will try and explain why (if not, read up on polymorphism).

But as far as your problem goes you could do something like:

code:
String getAggregateDescription() {
    return super.getAggregateDescription() + ", " + "blue";
}
for each of the subclasses.

Twitchy fucked around with this message at 22:41 on Apr 24, 2008

Twitchy
May 27, 2005

Save the whales posted:

I don't see why a ClassCastException would get thrown. foo is a BlueThing, a ColoredThing, and an ExtendableThing so I don't see a problem there.

Oops yeah you're right there, thought it was the abstract class. My apologies, always jumping the gun and looking the fool :argh:.

There's nothing else you need to put in the ExtendableThing getAggregateDescription(), since it will always call the most specific method.

So for example in ColoredThing you could have:

code:
String getAggregateDescription() {
    return super.getAggregateDescription() + ", " + "colored"
}
in BlueThing have:

code:
String getAggregateDescription() {
    return super.getAggregateDescription() + ", " + "blue"
}
in ShineyBlueThing have:

code:
String getAggregateDescription() {
    return super.getAggregateDescription() + ", " + "shiney"
}

Twitchy fucked around with this message at 22:55 on Apr 24, 2008

Twitchy
May 27, 2005

Save the whales posted:

This is what I have so far, but it's not working like I expected (it appears to cause infinite recursion):

I'm not sure if this is the root of the problem but even when you upcast a ShineyBlueThing to say a BlueThing, it will still call the ShineyBlueThing getDescription() method, rather than the upcasted version (i.e. it will always print "shiny"). I think you mentioned this above, so i'm gonna have a look over it, but I don't see any "easy" way of it being done :(.

The reason it doesn't work (at least part of it) is that you're saying getClass() << ShinyBlueThing .getSuperClass() << BlueThing .getMethod("getAggregateDescription") << which doesn't exist in the BlueThing class. Even then I don't think it's quite right, you're attempting to call the same method recursivly, while at the same time not actually changing anything that would make the method path any different.

The problem may just lie in the fact that you are upcasting instead of using a new object, as in:

code:
ExtendableThing foo = new BlueThing();
System.out.println(foo.getAggregateDescription());

foo = new ShineyBlueThing();
System.out.println(foo.getAggregateDescription());
I'm not sure if this is some requirement that it has to be able to do, but if you are just going to be instantiating objects of it's subclassed types it should be ok?

Also stupid little thing but I don't think:

code:
  if (getClass() == ExtendableThing.class)
  {
    return "";
  }
should be needed since you can't instantiate ExtendableThing in the first place.

Edit: Jesus christ, sorry this post is all over the place :|

Twitchy fucked around with this message at 23:47 on Apr 24, 2008

Twitchy
May 27, 2005

Save the whales posted:

I think I've got it! At least, this solution appears to work. I avoid the problem of the method being overwritten by declaring new instances of the super classes and abandoning recursion.

I actually thought of something like that aswell, whether it's usable depends on how often it'll be called, and any memory restrictions etc, since it's hacked together code. Another option would be to make the getDescription() static, since it looks like the value would be a constant anyway. It would also mean you wouldn't clutter up space with immediately discared objects. Just food for thought. That would have to be a stated requirement though, so if it wasn't implemented it could cause trouble.

Twitchy fucked around with this message at 00:18 on Apr 25, 2008

Twitchy
May 27, 2005

CrusaderSean posted:

Alright, apparently I don't understand how primitives and objects are passed to methods in Java. I thought Java only passes values to methods. But if I pass in an object like array, the object's content will change. For example:

Arrays are themselves Objects, and so are passed by reference. The array may contain primitives (ints, doubles etc), but the structure that holds them is an Object.

Twitchy fucked around with this message at 00:27 on Apr 25, 2008

Twitchy
May 27, 2005

CrusaderSean posted:

but if I change the scaleLine method to the following, the line array doesn't change... so if object parameters are really passed in as reference, shouldn't it point to the new int[] newLine?
code:
	void scaleLine2(int[] l, int s) {
		s = 40;
		int[] newLine = new int[2];
		newLine[0] = -2; newLine[1] = -2;
		
		l = newLine;
	}

Hah, I think this same question was just asked on the last page, and being a master of words made a mess off explaining it, but basically:

When you call scaleLine2, the REFERENCE (i.e. a place in memory where the object can be found) of l in the main method is assigned to a new variable called l. So when you say "l = newLine" you're basically saying "forget that last reference I gave you, use this one instead". So now your temporary variable l refers to the new int[] you made, where as l in the main method still refers to the same location as before.

Twitchy
May 27, 2005

PianoDragn posted:

* IMPORTANT: Performance is very important, please make the method efficient *

I am making an app right now and could use the following Graphics2D wrapper methods (I don't know a thing about Graphics2D)

1.) I want a method called applyOpacity(Image,Double) where it accepts an Image type and a double specifying the opacity. It will then use Graphics2D to apply the opacity to the Image and return the new Image. I don't know if this is possible or not, if it can't be stored in an image and instead needs to be stored in a Graphics object then return that instead.

2.) applyLighting(Image,Int) I send it an image with a brightness 0 being completely black and 100 being completely white? It then returns the resulting Image.

The useage would be if I wanted to bring something ot the foreground I would draw my background on offscreen image, pass it to the lighting method and darken it. Then I would take my 2nd image thats foreground send it to opacity and drawImage onto the offscreen image.

Thanks!

I have no idea of the performance of this method, but this is how I got it working:

code:
public Image applyOpacity(Image img, double opacity) {
    int w = img.getWidth(null);
    int h = img.getHeight(null);

    float[] scales = { 1f, 1f, 1f, (float)opacity };
    float[] offsets = new float[4];

    RescaleOp rop = new RescaleOp(scales, offsets, null);

    BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = (Graphics2D)bi.getGraphics();

    BufferedImage temp = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
    temp.getGraphics().drawImage(img, 0, 0, null);

    g2d.drawImage(temp, rop, 0, 0);
	
    return bi;
}
You'd be better off using a float to determine the opacity since that is what the RescaleOp uses, but since you said double I just cast it to that anyway. You could also edit the parameters to include light / darkness aswell I believe, using the scales array. Originally I had an "if (img instanceof BufferedImage)" to save on having the temp BufferedImage but I got the following error:

code:
Number of scaling constants does not equal the number of of color or color/alpha  components
Anybody know why it throws that? Playing around with images has never been my strong suit.
There's more info on this kind of method here: http://java.sun.com/docs/books/tutorial/2d/images/drawimage.html

Twitchy fucked around with this message at 17:02 on Apr 25, 2008

Twitchy
May 27, 2005

ssergE posted:

Hello All,

I am just about to start on some Java projects again, and was wondering what a good book would be for somebody with strong programming knowledge. I am after something akin to the classic K&R C book, but for Java. It should cover Java 1.6.

I own the 6th (I think - they are in storage ATM) editions of Horstman & Cornell's "Core Java" Vol 1+2. I was pretty impressed, and was wondering if anyone thinks the latest ones would be worth a purchase - or if they are considered pretty good?

I am after the type of book that isn't a "this is how to program", but more of a tour of the libraries and the correct Java way of doing things.

Thanks in advance.

The 2nd edition of Effective Java by Joshua Bloch is out, you might want to check that out. It doesn't neccesserally go in depth into the API's but it will give you a greater knowledge of how to use Java, as it happens, effectively.

Twitchy fucked around with this message at 11:58 on Jun 2, 2008

Twitchy
May 27, 2005

shodanjr_gr posted:

I am writting a small desktop search app. Im getting my results fine and dandy, and what i am trying to do, is launch my results, through my GUI. So if i get a .doc as a result, i wanna be able to launch whatever app my user has associated with .doc files (be it openoffice, ms word or wordpad). I also want to be able to do an "open containing folder" operation for each of my results.


The way you worded your previous reply, i got the impression that you have to know beforehand what programs are used for each filetype, and then issue a command-line call for those programs (passing the file to be opened as a parameter), which would make an application impossible to develop, considering the limitless combinations of file types and applications.



edit:

Found what i needed

code:
Runtime run = Runtime.getRuntime();
Process p = run.exec("cmd.exe /C "+this.my_file.getCanonicalPath());
This does what i want exactly wanted (with a drawback of the spawned application instances being child instances to the original java app...so the app doesnt completely shutdown until the children are closed...any way to get around that?).

http://java.sun.com/developer/technicalArticles/J2SE/Desktop/javase6/desktop_api/

How about this using this API? I haven't tried it myself but it does say:

quote:

Specifically, the new Desktop API allows your Java applications to do the following:

Launch the host system's default browser with a specific Uniform Resource Identifier (URI)

Launch the host system's default email client

Launch applications to open, edit, or print files associated with those applications

Edit: Just tested and it worked fine for both .doc and .jpg, so you might want to check it out considering it should be platform independent and it's not a child of the Java application.

code:
Desktop d = Desktop.getDesktop();

try {
    d.edit(new File("Untitled.jpg"));
} catch (IOException ex) {
    // exception
}

Twitchy fucked around with this message at 12:20 on Jun 2, 2008

Twitchy
May 27, 2005

epswing posted:

WHY?

You are looping over all the input / output in the seperate threads, but updating them all on the Event Dispatch thread (i.e. SwingUtilities.invokeLater(), which is the same no matter what JFrame you're using). Because you're looping over and invoking the Event Dispatch thread constantly it's locking up the other GUI. Could you not invoke the append() method at the end, and save the looping part in a StringBuilder or something?

Like:
code:
StringBuilder sb = new StringBuilder();
InputStreamReader isr = new InputStreamReader(input);
BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null) {
    sb.append(line + "\n");
}
br.close();
isr.close();
motherfucker.append(sb.toString());
Would mean the Event Dispatch thread wouldn't be getting thrashed with what could be hundreds of lines or whatever, but it depends if you need the lines to appear in "real time".

Twitchy fucked around with this message at 00:06 on Jun 4, 2008

Twitchy
May 27, 2005

zootm posted:

Batching the input would probably be a good idea, but waiting until the entire stream is read absolutely would not fit this use-case; it would only show anything once the processes had completely stopped.

Furthermore the invokeLater method just appends update events to the queue, unless there was a lot of events (which the last post shows that there really isn't) you can't really block the UI thread like that. And even then I don't think the effect would be the one shown there.

epswing: I'm still worried that the stream reader stuff is running in the UI thread for some reason (the symptoms fit too well, dammit). Can you breakpoint on it (any line) in a debugger and check the full stacktrace doesn't have any Swing stuff in it?

I guess you're right, I just assumed that because the GUI was noticably locking then the processes would have to have been taking a long time (therefore probably alot of lines to parse and a ton of events added to the queue). I just thought adding what could be thousands of events to the Event Queue could have an adverse effect, especially if alot of events are queued in front of his mouse click or whatever; I'm not exactly sure of the size of the input / output streams though. I didn't think the batching of the lines would be appropriate but it's an option, even having a progress bar would suffice if there were too many lines to process, especially since the user would only see lines whizzing past anyway.

Edit: Doh, it just clicked on what he's trying to do, I guess it wouldn't be appropriate.

Instead of doing a proper debug if you want the easy way to find out just do
code:
System.out.println(Thread.currentThread().getName());
to find out if it's running on an independent thread.

epswing posted:

:psyduck:
Ah, it seems zootm is probably right, how are you making the threads?

Twitchy fucked around with this message at 11:32 on Jun 4, 2008

Twitchy
May 27, 2005

epswing posted:

Here's another one for you, the two jframes are basically two separate programs, each running in their own javaw.exe with their own main method, etc.

How is this possible.

It's possible that ProcessBuilder launches subprocesses which would still be run under the same JVM instance, so only 1 Event Dispatch thread would exist between processes; honestly I don't know enough about ProcessBuilder for it to be anything other than a guess. I know JFrames appear as their own application in Task Manager but I haven't checked if they run in a seperate process or not normally so i'll check that out later.

Can you post the code you're using to launch the motherfucker process through ProcessBuilder?

Twitchy fucked around with this message at 17:20 on Jun 4, 2008

Twitchy
May 27, 2005

Phillyt posted:

Where can I find the source code for an API library or whatever? I'm trying to find one of the packages in javax.swing but I haven't had much look with Google or looking in my own folders.

If you have the JDK installed most IDE's will let you right click the Class name and goto the source code.

Twitchy
May 27, 2005

mister_gosh posted:

Thanks for the info. I am using Netbeans (6x) and trying to work through the interface to try to get it to do what you describe. I'll let you know how it goes once I find out how to create the property and find the dropdown (I think I've been staring too long at the screen!).

Aswell as the reasons zootm said before, there is another major reason why it's not working at all:

code:
jList1.setModel(new javax.swing.DefaultListModel() {
	String[] strings = { "DUMMY" };

	public int getSize() {
		return strings.length;
	}

	public Object getElementAt(int i) {
		return strings[i];
	}
});
Is overriding your getElementAt() method to only return elements in the "string" array, same with the getSize() method (which only ever returns 1, this is different from dlm.size()). Really it doesn't seem like you should have to sub class it at all, and if you want the "DUMMY" list item there to begin with, just use the addElement() method after you've created the DefaultListModel.

code:
DefaultListModel dlm = new DefaultListModel();
dlm.addElement("DUMMY");
jList1.setModel(dlm); // change to these lines

jList1 = new javax.swing.JList(dlm); // remove this line
jList1.updateUI(); // i don't think you need these
jScrollPane1.updateUI(); // ditto
Edit: and just a little pointer, avoid the line numbers as it's harder to paste for someone trying to help ;)

Twitchy fucked around with this message at 21:02 on Jun 10, 2008

Twitchy
May 27, 2005

mjan posted:

Not exactly - all variables are passed by value, but in the case of non-primitives the value happens to be an internal pointer to an object instance. It's a subtle but important distinction that makes it possible to reassign a variable within a different scope without affecting the object reference outside of said scope.

Oh god not this again (not saying you're wrong, but this topic always turns into a derailing clusterfuck in CoC)!

Twitchy
May 27, 2005

Startacus posted:

Can someone help me fix this little problem?

You could either firstly split the values into individual lines then split based on the coma into a new array, or use regular expression in the split method like split("[,\\n]") (I haven't tested that this works but it should be alright).

Also it seems odd that you have 2 different pieces of information in the same array, you'd probably be better making a small class with name and grade fields and have an array of those to store the information. Depends what you're doing it for I guess :).

Twitchy fucked around with this message at 14:51 on Aug 11, 2008

Twitchy
May 27, 2005

Clanpot Shake posted:

Say I was writing a program that was only allowed to run for an amount of time only known at run time. How would I get the program to clock itself and terminate when it was supposed to?

Use the Timer class: http://java.sun.com/j2se/1.4.2/docs/api/java/util/Timer.html

Add a TimerTask which just closes the application when it's run, and set the delay to whatever it is set to at runtime.

epswing posted:

You could extend the JPanel class, something like

Why extend JPanel? If you want it as an array of buttons on a grid extend JButton, JPanel is a container for multiple components. Or if you don't want it to function like an actual button extend JComponent.

Twitchy fucked around with this message at 16:25 on Dec 7, 2008

Adbot
ADBOT LOVES YOU

Twitchy
May 27, 2005

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

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

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

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

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

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

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

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

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

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