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
baka kaba
Jul 19, 2003

PLEASE ASK ME, THE SELF-PROFESSED NO #1 PAUL CATTERMOLE FAN IN THE SOMETHING AWFUL S-CLUB 7 MEGATHREAD, TO NAME A SINGLE SONG BY HIS EXCELLENT NU-METAL SIDE PROJECT, SKUA, AND IF I CAN'T PLEASE TELL ME TO
EAT SHIT

Yeah, try expanding each piece of that into a description of what you're checking or what you're doing. Make sure your logic is consistent, and then make sure each bit of code is doing what you want it to.

Your trigonometry code seems like it would only work in a specific case - the ball bouncing off the sides of the box at 45-degree angles, moving clockwise, always hitting each side in a fixed sequence. Like for example, if your ball was just moving horizontally, with no vertical velocity, you'd expect it to ping right back at 180 degrees, with the vertical speed unchanged. Right now your code just forces a 90-degree change in a fixed direction, which in this case means straight up or down.

So imagine that path line going horizontally straight into the wall, and then straight up, like a fixed right-angle. Now imagine tilting the whole thing up, so the incoming path is coming in from a higher point at a downward angle. What happens to the other part, after its 90-degree left turn? Where's it going? What's your code going to see the next time around?

The velocity angle idea is cool, you just need to make sure you're calculating changes to it correctly. You only have horizontal and vertical sides to worry about, so just get a diagram with the angle quadrants, and have a think about how a bounce off each side changes an angle, and what that means in terms of pi

baka kaba fucked around with this message at 19:03 on Aug 25, 2014

Adbot
ADBOT LOVES YOU

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.
Also known as "Rubber Duck Debugging"

Volmarias
Dec 31, 2002

EMAIL... THE INTERNET... SEARCH ENGINES...

Zaphod42 posted:

Also known as "Rubber Duck Debugging"

The best debugging, but it seems to work best when bugging a real person.

FieryBalrog
Apr 7, 2010
Grimey Drawer
This might be a nitpick, but this bothers me
code:
for (Circle fromArray : listOfCircles) 
Can't we just have (Circle circle : listOfCircles)

emanresu tnuocca
Sep 2, 2011

by Athanatos
Yeah we can but my teacher is somewhat pedantic and claims such names are confusing, I agree that it's actually much more legible the way you wrote it.

So I didn't create local variables but I understood from you guys' comments that I should perform the calculations in accordance to the 'collision case', my trigonometry is rusty and the math is all wrong but this makes more sense:
code:
				if (fromArray.x > getWidth()  - fromArray.radius) {
					fromArray.x = getWidth() - fromArray.radius + 1;
					fromArray.velDirecction += 2 * Math.asin(Math.sin(fromArray.velDirecction) * (-1));
				}
				if (fromArray.y > getHeight() - fromArray.radius + 1) {
					fromArray.y = getHeight() - fromArray.radius + 1;
					fromArray.velDirecction += 2 * Math.acos(Math.cos(fromArray.velDirecction) * (-1));
				}
				if (fromArray.x < 1) {
					fromArray.x = 2;
					fromArray.velDirecction += 2 * Math.asin(Math.sin(fromArray.velDirecction) * (-1));
				}
				if (fromArray.y < 1) {
					fromArray.y = 2;
					fromArray.velDirecction += 2 *  Math.acos(Math.cos(fromArray.velDirecction) * (-1));
				}
I probably shouldn't do the arcsin/arccos. The idea was just to reverse the direction on the axis where collision occurred but I still had issues and started messing things up, eventually all circles seem to lock to movement on the horizontal axis only. It's kind of interesting.

Yeah I should definitely figure out the correct math before tinkering with the code.

Thanks for the tips guys.

TheresaJayne
Jul 1, 2011
I would actually be more likely to use for(Circle circleFromArray : listOfCircles)

as fromArray doesn't say WHAT is fromArray ...

pigdog
Apr 23, 2004

by Smythe

TheresaJayne posted:

as fromArray doesn't say WHAT is fromArray ...

Yeah, that's wtfdumb.

Spatial
Nov 15, 2007

emanresu tnuocca posted:

I probably shouldn't do the arcsin/arccos.
I'll go one further: you shouldn't use angles at all. Angles are a horrendous way to represent direction, the only upside is familiarity with the bare numbers.

Vectors make everything much easier. In the general case you could use the reflection formula for light to bounce vectors around. In this special case where the walls are always at 90 degree angles you can turn your intuition directly into code: just as you said, when a circle hits a wall its motion on the contacting axis is negated. When the motion is a vector that's just negating a variable. :buddy:

emanresu tnuocca
Sep 2, 2011

by Athanatos

Spatial posted:

I'll go one further: you shouldn't use angles at all. Angles are a horrendous way to represent direction, the only upside is familiarity with the bare numbers.

Vectors make everything much easier. In the general case you could use the reflection formula for light to bounce vectors around. In this special case where the walls are always at 90 degree angles you can turn your intuition directly into code: just as you said, when a circle hits a wall its motion on the contacting axis is negated. When the motion is a vector that's just negating a variable. :buddy:

Yeah that was kind of unnecessary I guess, I'd still love not sucking at math as much but after switching "velocity" to simply be a double[2] and ignoring the whole 'velDirection' bullshitery everything worked perfectly within 2 minutes.

So yay!

baka kaba
Jul 19, 2003

PLEASE ASK ME, THE SELF-PROFESSED NO #1 PAUL CATTERMOLE FAN IN THE SOMETHING AWFUL S-CLUB 7 MEGATHREAD, TO NAME A SINGLE SONG BY HIS EXCELLENT NU-METAL SIDE PROJECT, SKUA, AND IF I CAN'T PLEASE TELL ME TO
EAT SHIT

Is your position checking right? That's what I was alluding to when I said you should write your logic out as short descriptions of what you need to do - it seems really inconsistent. Sometimes you're compensating for the particular circle's radius, sometimes it's a hardcoded value, sometimes it's both!

Maybe it works out, but it's better to make things work for a general case, where you calculate the things you need to check from the data you're working with. Like in this case, you're basically taking the centre of some ball you're given, as x and y coordinates, and checking that the ball's top, left, bottom and right sides haven't gone through the top, left, bottom and right walls.

So you need to take your centre point, work out where those ball sides are (which depends on the size of the ball), and compare them to the position of the wall they might hit (which depends on the dimensions of the walled area). You can calculate all the values you need to compare from the info you're given (ball position, ball radius, width and height of the place), and if they ever change your code will spit out the appropriate values and compare the right things.

You might want to hardcode some numbers sometimes, say a fixed distance from each wall that counts as a collision (like a buffer zone or something), but in that case you should declare it as a constant with a nice readable name, then use that constant in your code. If you ever want to change that fixed value, there's only one place you need to do it! Also comment (explain) everything

emanresu tnuocca
Sep 2, 2011

by Athanatos
Thanks, I understand the importance of writing a more legible code and sticking to conventions, in this particular example I was just trying to screw around a bit and have colorful balls jumping all over the place so I didn't mind tinkering with 'brute force', I do agree with everything you said though.

And now I have some different questions pertaining to Swing.

We were tasked with designing and implementing a user interface for a 'schedule manager' (personal diary?), I already have the scheduler written and working rather perfectly with a console/text based user interface and I had some 'creative' ideas I wanted to explore in regards to the graphic user interface, so I want to code some transitional animations and have some questions:

1. Say I have a JFrame with several JPanels attached to it, I'm trying to create a method that allows me to expand one Panel while contracting every other panel, so I tried using JFrame.getComponents() and iterating over the panels with a for loop, but even though I have 3 panels attached to the frame getComponents() doesn't seem to work, that is it never enters the loop. Am I missing something? Would it simply be better to create a field (ArralyList<JPanel>) that holds references to all attached panels (can create an add(JPanel) metod that calls add(component) while maintaining this reference list)?

2. As I want to create transitional animations, should I use a TimerTask? Or would it be better to create a simple loop that just uses System.CurrentTimeMilis() to do the transitions?

Please let me know if these questions are not clear and attach some relevant code snippets. And once again, thank you all for your help.

emanresu tnuocca
Sep 2, 2011

by Athanatos
Hey guys,

Different question, I'm trying to load a .png resource and use it as an icon but I'm getting an exception:
code:
Uncaught error fetching image:
java.lang.NullPointerException
	at sun.awt.image.URLImageSource.getConnection(Unknown Source)
	at sun.awt.image.URLImageSource.getDecoder(Unknown Source)
	at sun.awt.image.InputStreamImageSource.doFetch(Unknown Source)
	at sun.awt.image.ImageFetcher.fetchloop(Unknown Source)
	at sun.awt.image.ImageFetcher.run(Unknown Source)
my code is very simple and as far as I can tell the .png is found in the right folder

code:
		URL imgURL = this.getClass().getResource("./images/expand.png");
		Image expImg = Toolkit.getDefaultToolkit().createImage(imgURL);
the image is in the source folder under "images". So I can't figure out what's the problem exactly, any pointers?

Volguus
Mar 3, 2009
Most likely this would work:

code:
		URL imgURL = this.getClass().getResource("/images/expand.png");
(I removed the leading dot from the path).

emanresu tnuocca
Sep 2, 2011

by Athanatos
Argh, I placed the folder inside project/src/package, apparently it should just be at project/

oh well.

emanresu tnuocca
Sep 2, 2011

by Athanatos
Sorry for spamming this thread with questions, I hope nobody minds too much.

I have a small problem with using an ArrayList, I had an existing project that used arrays to store objects and I wanted to switch all those annoying arrays to ArrayLists, all the classes stored in those arrays inherit from one abstract class, the thing is that one of those inheriting classes implements Comparable, and I'm required to be able to sort the ArrayList containing this inheriting class, but as the abstract superclass isn't comparable and I can't seem to cast between ArrayList<Abstract Class> to ArrayList<inheriting 'comparable' class> I feel like I might be missing something.

I can think of several ways to solve this but I feel like I'm missing something rather trivial and shouldn't start copying arrays or implementing Comparable in the abstract superclass, any hints?

carry on then
Jul 10, 2010

by VideoGames

(and can't post for 10 years!)

Cast after you pull the items out of the arraylist.

Java code:
ArrayList<AbstractClass> items = getComparableObjects();
boolean swapped = true;
while (swapped) {
    swapped = false;
    for (int i = 0; i < items.length() - 1; i++) {
        if (((ComparableClass)items.get(i)).compareTo((ComparableClass)items.get(i + 1) > 0) {
            swap(items.get(i), items.get(i + 1));
            swapped = true;
        }
    }
}
This is a case of Java being somewhat inflexible here; that if statement's a mess. Having the abstract class implement comparable would make the code cleaner.

carry on then fucked around with this message at 21:15 on Sep 1, 2014

Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."
emanresu tnuocca: I'm very confused as to why the abstract superclass couldn't implement Comparable- the contract you're expressing with those types is at odds with what you want to do, so it makes sense that it ends up clumsy.

carry on then: If you defined your own Comparator at least you wouldn't have to implement a bubble sort from scratch like that:
Java code:
Collections.sort(items, new Comparator<AbstractClass>() {
	public int compare(AbstractClass a, AbstractClass b) {
		return ((ComparableClass)a).compareTo((ComparableClass)b);
	}
});
Assuming a relationship like:
Java code:
class AbstractClass {
	...
}

class ComparableClass extends AbstractClass implements Comparable<ComparableClass> {
	public int compareTo(ComparableClass other) { ... }
}

Volguus
Mar 3, 2009
Is there a problem with List<? extends Comparable> ? Or List<? extends MyAbstractThing> ?

Also, just as an advice, try to not work with ArrayList directly (requiring it as a parameter to a method, or returning it from a class). Work, if you can, with List or, even better, Collection.

Generally, when you need a container, think about what do you need to do with that container. That should tell you exactly what interface you should require. For example, if all I need with a container is to iterate through its members, then requiring an Iterable is the most I should ask for. If I need methods such as add, clear, remove, size, then I definitely need a Collection. If I need get(index) for example, then I need List. Or, Set for when I need the items to be unique.

When returning a container interface it allows you to change the implementation any time you wish (from ArrayList to LinkedList or to ConcurrentList if the requirements change). By asking from others for a container interface (as a parameter passed to you), you allow them to use whatever implementation they wish.

carry on then
Jul 10, 2010

by VideoGames

(and can't post for 10 years!)

Internet Janitor posted:

emanresu tnuocca: I'm very confused as to why the abstract superclass couldn't implement Comparable- the contract you're expressing with those types is at odds with what you want to do, so it makes sense that it ends up clumsy.

carry on then: If you defined your own Comparator at least you wouldn't have to implement a bubble sort from scratch like that:
Java code:
Collections.sort(items, new Comparator<AbstractClass>() {
	public int compare(AbstractClass a, AbstractClass b) {
		return ((ComparableClass)a).compareTo((ComparableClass)b);
	}
});
Assuming a relationship like:
Java code:
class AbstractClass {
	...
}

class ComparableClass extends AbstractClass implements Comparable<ComparableClass> {
	public int compareTo(ComparableClass other) { ... }
}

It was just a demonstration.

Spatial
Nov 15, 2007

If they all implement some common interface, you can make an ArrayList<CommonInterface> and put any implementing class in there.

e: soo late. :shobon:

emanresu tnuocca
Sep 2, 2011

by Athanatos

Internet Janitor posted:

emanresu tnuocca: I'm very confused as to why the abstract superclass couldn't implement Comparable- the contract you're expressing with those types is at odds with what you want to do, so it makes sense that it ends up clumsy.

Well, in this case it's basically just a bunch of containers where only the bottom-level object in the hierarchy is comparable, for reference it contains a LocalDate field where all the other objects in the hierarchy don't, so yeah I could implement Comparable on the abstract class but it would be rather meaningless for anything other than single inheriting class with the LocalDate field.

I was originally using Arrays.sort and would indeed like to use Collections.sort.


rhag posted:

Is there a problem with List<? extends Comparable> ? Or List<? extends MyAbstractThing> ?

Also, just as an advice, try to not work with ArrayList directly (requiring it as a parameter to a method, or returning it from a class). Work, if you can, with List or, even better, Collection.

Generally, when you need a container, think about what do you need to do with that container. That should tell you exactly what interface you should require. For example, if all I need with a container is to iterate through its members, then requiring an Iterable is the most I should ask for. If I need methods such as add, clear, remove, size, then I definitely need a Collection. If I need get(index) for example, then I need List. Or, Set for when I need the items to be unique.

When returning a container interface it allows you to change the implementation any time you wish (from ArrayList to LinkedList or to ConcurrentList if the requirements change). By asking from others for a container interface (as a parameter passed to you), you allow them to use whatever implementation they wish.

Thanks for the advice regarding containers, I'll mull over it.

Yeah I was wondering if generics were the way to go here, but I'm still confused as to how to run it through Collections.sort?

code:
public abstract class AbstractElement{
public abstract ArrayList<? extends AbstractElement>;
}
The way I figure it out (which is probably all wrong), if I have an <? extends AbstractElement> arraylist that only contains the 'low level object' (which is comparable) I'm still gonna have to copy it to a new collection with <LowLevelObject> (or otherwise bubble sort through it with casting).

carry on then
Jul 10, 2010

by VideoGames

(and can't post for 10 years!)

emanresu tnuocca posted:

Well, in this case it's basically just a bunch of containers where only the bottom-level object in the hierarchy is comparable, for reference it contains a LocalDate field where all the other objects in the hierarchy don't, so yeah I could implement Comparable on the abstract class but it would be rather meaningless for anything other than single inheriting class with the LocalDate field.

I was originally using Arrays.sort and would indeed like to use Collections.sort.


Thanks for the advice regarding containers, I'll mull over it.

Yeah I was wondering if generics were the way to go here, but I'm still confused as to how to run it through Collections.sort?

code:
public abstract class AbstractElement{
public abstract ArrayList<? extends AbstractElement>;
}
The way I figure it out (which is probably all wrong), if I have an <? extends AbstractElement> arraylist that only contains the 'low level object' (which is comparable) I'm still gonna have to copy it to a new collection with <LowLevelObject> (or otherwise bubble sort through it with casting).

So what you're saying is that you have an ArrayList that holds objects of any of several classes which implement AbstractElement, only one of which implements Comparable? It looks like you say that the list you need to sort is guaranteed to only have objects of this Comparable subclass, right? Do you know in advance which ArrayList this will be? If so, you could probably get away with making an ArrayList<ComparableElement> in this case only and sorting that list. If you later needed to store those objects in an ArrayList<AbstractElement> this would be possible without any special casting since ComparableElement extends AbstractElement.

There's a better solution here, but without knowing the specifics of how you get these objects, when you sort them, and what you do with them afterwards, it's difficult to say what that might be.

pigdog
Apr 23, 2004

by Smythe

emanresu tnuocca posted:

Sorry for spamming this thread with questions, I hope nobody minds too much.

I have a small problem with using an ArrayList, I had an existing project that used arrays to store objects and I wanted to switch all those annoying arrays to ArrayLists, all the classes stored in those arrays inherit from one abstract class, the thing is that one of those inheriting classes implements Comparable, and I'm required to be able to sort the ArrayList containing this inheriting class, but as the abstract superclass isn't comparable and I can't seem to cast between ArrayList<Abstract Class> to ArrayList<inheriting 'comparable' class> I feel like I might be missing something.

I can think of several ways to solve this but I feel like I'm missing something rather trivial and shouldn't start copying arrays or implementing Comparable in the abstract superclass, any hints?

You don't need to implement Comparable to use or sort your objects in ArrayList (though you do for TreeList). Look at Internet Janitor's post; use your own Comparator argument to Collections.sort() to sort the list whichever way you want. Suppose you want to sort your list by other criterias than just one - then you'd just need use a different Comparator that compares different aspects of the objects.

CarrKnight
May 24, 2013
Hope this is the right thread to ask this.

So I code agent-based models. Which you can just imagine being complicated 2d games.
I code them in Java I like structured object oriented programming.

My issue is with deployment.
I want other people to use my models. To "play" my games.
Few years ago all I had to do was to place a java applet somewhere and people could just use my model straight from a web-page.
Now applets only work if I pay hundreds of dollars to Verisign to sign them.

I'd like another way to code the gui so that anybody can use my model just by connecting to a web-page hosting it. The GUI can be any language. I am willing to learn. The "backend" model has to stay Java though.
I am really confused. Is there any technology that allows this? Mind you: these aren't web-apps. There is no server/communication involved. You download your 10mb model and you are good to go.

Suggestions on the tech to use to code the gui?

Volmarias
Dec 31, 2002

EMAIL... THE INTERNET... SEARCH ENGINES...
If you're ok with people downloading the app, why not just make a jar, or whatever the new-fangled web-start stuff is called nowadays?

Volguus
Mar 3, 2009

CarrKnight posted:

Hope this is the right thread to ask this.

So I code agent-based models. Which you can just imagine being complicated 2d games.
I code them in Java I like structured object oriented programming.

My issue is with deployment.
I want other people to use my models. To "play" my games.
Few years ago all I had to do was to place a java applet somewhere and people could just use my model straight from a web-page.
Now applets only work if I pay hundreds of dollars to Verisign to sign them.

I'd like another way to code the gui so that anybody can use my model just by connecting to a web-page hosting it. The GUI can be any language. I am willing to learn. The "backend" model has to stay Java though.
I am really confused. Is there any technology that allows this? Mind you: these aren't web-apps. There is no server/communication involved. You download your 10mb model and you are good to go.

Suggestions on the tech to use to code the gui?

If you don't want access to user's computer, you don't need to sign your applet. Why would you need access to user's computer? With that being said, I wrote recently a web-start app for internal use at my company that is self-signed (i need access to the microphone). With newer version of the JRE installed, they had to specifically say they trust the server in the Control Panel applet.

If you wanna change the UI, in HTML 5 you can do quite nifty things with WebGL and java script: https://www.unrealengine.com/html5 .

Volguus fucked around with this message at 12:48 on Sep 2, 2014

CarrKnight
May 24, 2013

quote:

With newer version of the JRE installed, they had to specifically say they trust the server in the Control Panel applet
Yes exactly. I'd need to tell my audience to go to their settings, lower them and so on. They aren't going to do it.
It's a pain. They'll just go somewhere else.

quote:

If you're ok with people downloading the app, why not just make a jar, or whatever the new-fangled web-start stuff is called nowadays?
Web-start requires signature or lowered security settings or both.
Download and run is my current modus operandi, but i really wish they could just run from the web.

quote:

If you wanna change the UI, in HTML 5 you can do quite nifty things with WebGL and java script: https://www.unrealengine.com/html5 .
This is what I hear, but how do I use an HTML5/javascript/webgl GUI over a java program? Is there a set of libraries?

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe
It doesn't interact with your java program like your thinking. You basically have to convert your Java program into a server that can send back json responses instead of whatever Java beans you were sending back to your UI.

CarrKnight
May 24, 2013
I'd imagine that killing all sorts of reactivity, right?
Is there a code example of a java-backed html5 2d game?

Volguus
Mar 3, 2009

CarrKnight posted:

I'd imagine that killing all sorts of reactivity, right?
Is there a code example of a java-backed html5 2d game?

There is no need. The server can run whatever it wants: perl, python, Java, php, c or c++. Or whatever other language you want. The only thing that matters is the response it provides to a request. For a game, one may want to save the score on the server every ... 100ms (just a number pulled out of my ... hat). Therefore, the javascript on the client (the browser) may send a request to the server with the updated score every 100ms. The server's job is to save that information and to reply with an 200 OK. Or if it cant ... reply with an appropriate error code.

There is no other connection between server and client in a javascript based application. You can write the server in javascript too if that floats your boat.

baka kaba
Jul 19, 2003

PLEASE ASK ME, THE SELF-PROFESSED NO #1 PAUL CATTERMOLE FAN IN THE SOMETHING AWFUL S-CLUB 7 MEGATHREAD, TO NAME A SINGLE SONG BY HIS EXCELLENT NU-METAL SIDE PROJECT, SKUA, AND IF I CAN'T PLEASE TELL ME TO
EAT SHIT

CarrKnight posted:

Yes exactly. I'd need to tell my audience to go to their settings, lower them and so on. They aren't going to do it.
It's a pain. They'll just go somewhere else.

Web-start requires signature or lowered security settings or both.
Download and run is my current modus operandi, but i really wish they could just run from the web.

Is your audience likely to even have the JRE installed and enabled? I mean I'm someone who codes in Java and if I see a webpage trying to run a Java applet, I usually say 'gently caress this poo poo' and hit that back button. Not saying I'm a representative sample or anything, and you know your audience, but if you're looking for ease of use I'd imagine you want something that just runs 'natively' in the browser?

It might help to describe your 'game' a bit too, there's a difference between something that can just send moves to a server vs something that needs to do a lot of responsive heavy lifting on the client

CarrKnight
May 24, 2013
First of all, thank you for all the answers.

quote:

Is your audience likely to even have the JRE installed and enabled? I mean I'm someone who codes in Java and if I see a webpage trying to run a Java applet, I usually say 'gently caress this poo poo' and hit that back button. Not saying I'm a representative sample or anything, and you know your audience, but if you're looking for ease of use I'd imagine you want something that just runs 'natively' in the browser
Exactly!

Okay, to clarify what I need. Imagine a very, very lovely sim-city. Take model-view-controller abstraction.

The model is the citizens, the markets, the rules of trading, the geography. All that stuff. It has to be in Java. This is because the end goal of these models is peer-review. And since others in my field code in Java, I need to do the same. I show up with go or dart and people just don't know what they are looking at.

The view and the controller, I'd like to be native in the browser. This makes for much easier prototyping and I can let my audience play with the model before it is complete and before they need to plunge into the source code.
I can code this in any language i see fit. Peers don't care.

Now, what I don't understand is, if I learn HTML5 or Javascript or whatever do I need to implement a server-client interaction? If so, what machine is actually running the model (the city simulation)?
That's what I liked about applets. It would just work out of the box.

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.
I mean, what are the inputs and outputs of your agent? It's kind of a vague question, and the right thing to do really depends on the specifics of what you want.

In the absence of all other information, The Thing That I Know How To Do is HTTP webservers, so I'd build up a quick-and-dirty Jersey server that does JSON de/serialization, and host it on Linode. I'd then write a Javascript app that interacts with the server. If kind-of-plain is good enough, I'd just do it with jQuery or something. If it is somewhat complex, I'd look into using Angular and a Grunt build system. This is assuming that text-box-and-buttons input is good enough. If you're trying to draw things, something like Flash might be a better option.

Chas McGill
Oct 29, 2010

loves Fat Philippe
Following on from this - marketing at work wants to create a bit of modelling software to visualise the effect of spend on oil platforms. Basically it'd be a picture that changes when the user moves sliders or inputs figures. Are there any good Java libraries for something like this, or should I be looking at another tool/language? Seems like flash would be the traditional thing, but I only have (limited) experience with Java.

emanresu tnuocca
Sep 2, 2011

by Athanatos
What's the conventional wisdom in regards to implementing ActionListeners? In the spirit of making my questions less obtuse I'll add some screenshots,

So I have my stupid TaskManager application:


At first each one of these panels implemented ActionListener and executed methods in my top-level frame class, I figured that was pretty stupid and changed it so that the toolbar and menubar no longer implement ActionListener and instead use the top-level frame as a Listener, no difficulties here.

However, when you click the add button you get a JDialog frame:


Pressing OK/Cancel, along with obviously disposing of the window, is also supposed to generate a new "TaskManagerElement" (i.e, category, task or subtask) for and add it to my data containing class, there's some logic involved in that such as checking out that there's enough space, sorting out the SubTask (yes the Collections.Sort question from earlier) and updating the JTree display, so most of its functionality relates to the main frame, however, for me to be able to create the window in one action and dispose of it in another, I'll probably need to turn the JDialog into a field in the main frame class.

Now it isn't a big deal but I'm starting to wonder if I'm doing the right thing, should I keep the JDialog's ActionListener implementation and have it execute methods in the main frame class? Is there even any convention here.

Thanks

Gul Banana
Nov 28, 2003

If a Java model is a hard requirement, then

CarrKnight posted:

Now, what I don't understand is, if I learn HTML5 or Javascript or whatever do I need to implement a server-client interaction?
yes

quote:

If so, what machine is actually running the model (the city simulation)?
the server.

In general there's no way to do general-purpose execution on the web client. Only specific exemptions exist: chrome's nacl, java applets before the security problems, flash until it dies... Unless you can fit into one of those holes, it's javascript only.

carry on then
Jul 10, 2010

by VideoGames

(and can't post for 10 years!)

emanresu tnuocca posted:

What's the conventional wisdom in regards to implementing ActionListeners? In the spirit of making my questions less obtuse I'll add some screenshots,

So I have my stupid TaskManager application:


At first each one of these panels implemented ActionListener and executed methods in my top-level frame class, I figured that was pretty stupid and changed it so that the toolbar and menubar no longer implement ActionListener and instead use the top-level frame as a Listener, no difficulties here.

However, when you click the add button you get a JDialog frame:


Pressing OK/Cancel, along with obviously disposing of the window, is also supposed to generate a new "TaskManagerElement" (i.e, category, task or subtask) for and add it to my data containing class, there's some logic involved in that such as checking out that there's enough space, sorting out the SubTask (yes the Collections.Sort question from earlier) and updating the JTree display, so most of its functionality relates to the main frame, however, for me to be able to create the window in one action and dispose of it in another, I'll probably need to turn the JDialog into a field in the main frame class.

Now it isn't a big deal but I'm starting to wonder if I'm doing the right thing, should I keep the JDialog's ActionListener implementation and have it execute methods in the main frame class? Is there even any convention here.

Thanks

The convention you're looking for is called a callback: http://en.wikipedia.org/wiki/Callback_(computer_programming). Your JDialog should hold a reference to the main frame that created it, and your main frame should have some method like AddTask(TaskManagerElement) that will do everything to get the task added. The JDialog calls this and passes the task over, then closes itself. It sounds like this is close to what you have now, and it's a common pattern in GUI applications.

carry on then fucked around with this message at 17:14 on Sep 3, 2014

CarrKnight
May 24, 2013

Gul Banana posted:

In general there's no way to do general-purpose execution on the web client. Only specific exemptions exist: chrome's nacl, java applets before the security problems, flash until it dies... Unless you can fit into one of those holes, it's javascript only.

Got it, thanks!

Volguus
Mar 3, 2009

carry on then posted:

The convention you're looking for is called a callback: http://en.wikipedia.org/wiki/Callback_(computer_programming). Your JDialog should hold a reference to the main frame that created it, and your main frame should have some method like AddTask(TaskManagerElement) that will do everything to get the task added. The JDialog calls this and passes the task over, then closes itself. It sounds like this is close to what you have now, and it's a common pattern in GUI applications.

In Java this is also known as a "listener" (look at jbutton ActionListener for example).

Adbot
ADBOT LOVES YOU

Yhag
Dec 23, 2006

I'm dying you idiot!
Hopefully a simple question:

Using Netbeans I created most of a small triangulation program for an assignment:



The grid is a seperate JPanel, relevant code:

code:
    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        g.setColor(Color.white);
        g.fillRect(35, 0, 600, 375);
        g.setColor(Color.black);
        g.drawRect(35, 0, 600, 375);
        g.setColor(Color.LIGHT_GRAY);

        for (int k = 0; k < 14; k = k + 1) {
            g.drawLine(36, 25 + k * 25, 634, 25 + k * 25);
        }

        for (int l = 0; l < 23; l = l + 1) {
            g.drawLine(60 + l * 25, 1, 60 + l * 25, 374);
            
        }
    }
On button click it calculates 2 coordinates xC and yC. I want to draw a line from (xA,yA) to (xC,yC) and from (xB,yB) to (xC,yC), relevant code:

code:
                    class jPanel2 extends Plot {

                        @Override
                        public void paintComponent(Graphics g) {
                            super.paintComponent(g);
                            g.setColor(Color.red);
                            g.drawline(xA, yA, xC, yC);
                            g.drawline(xB, yB, xC, yC);
                            Plot.repaint();

                        }
                    }


I run into two problems:

- Using Plot.repaint(); I get the following error:
non-static method repaint() cannot be referenced from a static context.
Googling it gets me solutions that are more complicated (to me) than this problem seems.

- Using doubles xA, yA, etc in the g.drawline() tells me:
incompatible types: posible lossy conversion from double to int
local variable xA is accessed from within inner class; needs to be declared final
.

My Java experience is pretty much zero so googling these errors doesn't really help much.

Thanks

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