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
Volguus
Mar 3, 2009

CT2049 posted:

I used to do all of my programming in Swing, I stopped using it about 2 years ago, so it may have improved since I stopped using it.

The problem I've seen with Swing is the tutorial applications you'll find online make it look like the easiest thing in the world. However, once you go beyond the simple one text box, one button, one label programs and start making anything remotely complex the the learning curve stops being a curve and turns into a brick wall. IDE's like NetBeans will try to hide a lot of the complexities but in the end they will harm you as you won't understand how to make your GUI dynamic.

Perhaps a book will help?
I remember applying for a job around 10 years ago (still a student), a Java programmer job. Being used with JBuilder (was version 2 or so at the time) and its designer, i never payed much attention to the GUI structure. At the job interview they gave me a very simple GUI app to do, in notepad.
I had a day. Could not make it to behave how i wanted to for the life of me.
The day after that (and not getting the job) I bought a Java Swing book (sorry, the name escapes me, there should be plenty of them now available). I learned a lot from it. What is a layout, how to use a layout properly and most importantly:
How to use GridBagLayout and how to make your own if none of them does what you need.
The MVC model is another thing I love the most in that library. I haven't found yet any other that is trying to even come close (in any other language), and its always pissing me off when I have to store the display string in the UI object and/or to store the data somewhere else.

Today, after using Java for almost 10 years now at work, I simply love Swing. I have used it in many projects. Is it worth learning over another technology? No clue. Today the Web2.0 stuff seems to be the buzz. In my view its a great way to learn Java, just by programming in Swing and looking over to the source code to see how did they do stuff.

Adbot
ADBOT LOVES YOU

Volguus
Mar 3, 2009

ynef posted:

Before learning Swing, it might be good for you to learn more about multithreaded (programs that do more than one thing at a time) programming. Not only is it really cool stuff, but you have to know it to make Swing programs. No exception, you need to know threads to do GUI programming.

Well...kinda, sorta and not really.
As it is the case with everything, it depends. For very simple programs, probably you don't have to worry about it. For more complex ones, where the chances of having a long operation to execute are high, yes, it is a must.
With Java 1.6 however, it's dumb easy to do multi-threading in Swing, and to be fairly safe (SwingWorker).
As the Swing Tutorial explains there are a couple of things that you always need to be aware of:
- All the event handling operations in Swing are executed in the event dispatch thread (EDT)
- All code that deals with Swing components should be executed in this thread
- A Swing component should not be modified in a different thread than the EDT

This is why:
- The main window of a swing application should be created and displayed using SwingUtilities.invokeLater(...)
- When performing lengthy operations, use SwingWorker's doInBackground method to do your stuff, and then override done() to get the results and display them.
- You can also listen for progress change using this class, and can also make incremental updates to a Swing component with the help of this class. Everything in a thread safe manner.


For general knowledge though, yes, you do need to know what are threads, semaphores, synchronization, etc., basically whats with this concurrency crap everyone hates but has to use.

Volguus
Mar 3, 2009

mister_gosh posted:

I need some guidance and want to know if this is feasible.

I want to have an application which is client and server based. The client app (Swing-based) will send some information to a servlet. The servlet will place the request in a queue. The individual request may have to wait up to 20 minutes in some instances (maybe even more). The client must maintain an active connection and perhaps get updates to a field in the Swing app. Once the request is processed (this could be a quick or a long process), information is sent back to the client.

Is this feasible? What should I utilize (such as looking into a work queue type process, or use a singleton in such a way that makes this possible)?

What I had wanted to do was have the servlet dump the request into a directory. Then a scheduled task would fire every few minutes and pick up the next request from that directory. Once finished, an email would be sent to the user with the request information. This process didn't seem to be enough for the person needing this application.

I am not sure if a servlet is the best way to go here.
You could implement your own server, with your own protocol, but probably is not worth the effort.
One idea would be to have either a RMI server or a web-service server. The client would make the request, and then it can check periodically what's the status.
Something like:
code:
//returns the ID of the task
public int queueTask(Task task);
//returns the Status (enum) of a task given its ID
public Status getTaskStatus(int id);
Then , the server part can be implemented in any way you want. Probably storing information in a database, where a thread could come and pick up new tasks every time its free. Or on a set schedule (Quartz?).

Just an idea, im sure it can be done in a billion other ways.

Volguus
Mar 3, 2009

sonic bed head posted:

Is there a way that I can get a simple date format or something else to print out something like "4th July 2007"? I can't find something that prints out days with "th" or "st" next to them but I feel like I'm missing something stupid. Thanks.

Never had that request from anyone, usually July 4,2007 is just fine (or Jul 04,2007). And that, as you probably already know, can be done with DateFormat (or SimpleDateFormat if you have a non-standard pattern).

And, surprisingly, not even creating your own DateFormatSymbols class will help you.

It looks like you have to create your own DateFormat implementation. (that will have to accept only English locales.... :))

Volguus
Mar 3, 2009
well, the official Java tutorial may be a good start: http://java.sun.com/docs/books/tutorial/index.html

Basically, it should work like this (command prompt):

javac HelloWorld.java

ls (or dir):
HelloWorld.java
HelloWorld.class

"java HelloWorld" should just work.

edit:
You may find it easier to use an IDE however (even if its not required). NetBeans and Eclipse are 2 of the most popular out there (and free).

Volguus fucked around with this message at 19:15 on Jun 8, 2009

Volguus
Mar 3, 2009

8ender posted:

It looks cool but does anyone else feel like we've come full circle here? It really does feel like an old fashioned applet.

There is quite a big difference between an applet and an application loaded via WebStart (JavaFX or not).

The applet runs within the browser, specified as an <object> tag. It is obviously subject to a very restrictive set of permissions. Before JDK 1.6 update 10, the applet would run in the same process as the browser, and all applets in a web page would run in the same JVM. After JDK 1.6 update 10 (Oct 2008) some changes occurred:
- Applets run in a separate process to the browser, and each applet can optionally run in a separate JVM instance
- Applets can have parameters passed to them to control behaviour, such as setting a large initial heap size to avoid out of memory exceptions
- Applets can now be dragged out of the web browser and run as separate applications

(this info I copied from http://big.faceless.org/blog/2009/01/05/1231151940000.html Credit goes to them :) )

Oh, and applets could be somewhat interacted with via javascript (and viceversa via a netscape library).

JNLP was always a bit different. Via WebStart the user would run a stand-alone desktop application. It would be sandboxed of course (can get out via signature), but you would not have an JApplet class, you needed to have a class with a "main" method,etc. It always ran in a separate process, and was not accessible via javascript.

But yes, lately the line between an applet and a WebStart launched application has been blurred quite a bit.

Volguus
Mar 3, 2009

sonic bed head posted:

Is it possible to programatically compile a JSP? I am using struts and I would like to dynamically make a jsp and then inject into it a request and get the value of the whole page as a huge string. Hopefully that makes sense. Basically I would like to be able to compile a jsp in the action without returning a jsp to the browser yet.

I am sure it's possible (no idea how, probably digging up the class that parses the JSP file in the tomcat distribution, and invoking that), but...why not create a servlet dynamically (JSP becomes a servlet anyhow, that gets compiled on the fly by tomcat)?
For that you'd only need to see the tools.jar for the javac compiler and invoke that.

That is, if you absolutely have to dynamically generate that. Since the details of what you have to do are zero, I can't say anything, but...are you sure there isn't a better solution?

Volguus
Mar 3, 2009

sonic bed head posted:

What I need to do is fairly complicated and I've been trying to piece it all together for weeks so let me try and explain.

I need to basically have dozens of forms each of which have complicated objects that aren't simple key value pairs. I need dozens of JSP's that correspond to each of these forms with completely different UI widgets (some are auto complete text boxes, some are multiselect boxes or textareas). Instead of actually making these dozens of jsp's that will be hell to maintain, I'm making a database driven UI. That would be fine if these JSP's were simple and I could use regular HTML, but the problem is that I need to use some struts tags to make this work correctly. The reason I need struts tags is that these forms don't really follow the regular http key/value pair idea, instead it is a more complicated object with nesting. Something like:
code:
{"id":123,
"object":{
"objparam1":"objvalue1",
"objparam2":"objvalue2"
}
}
Any idea how to better achieve what I'm trying to do?

edit:currently my very very clunky solution is to have html text input fields with names such as "123||||objparam1" and then split the name with "||||" and sort it in the backend, but that's getting more annoying to do when the nesting becomes deeper and I have things like "123||||category||||objgroup||||objparam1".


Ideally, you could have one JSP generate the form on the fly, depending on what form is requested. What fields, objects,etc. are needed in the form, that can be kept in the database. There will need to be a factory created, that would be able to tell the JSP in a form-independent manner how to create the form, and be able to save the data.
The problem is that something like this would become quite complex (as such hard to maintain). An established design pattern would certainly help reduce the complexity, but the entire mechanism will resemble more a framework than an application.

JSP generation can work as well, but drat, I find this extremely complex to maintain as well (just think about it. A bug comes up. Where's the bug? In the JSP? In the generator? In the settings?). I've done this (servlet generation) a long time ago (2001-2002) and it was painful.

The simplest approach (more mindless work though) would be to just create the dozens or so JSP's that are needed. A student could be assigned to maintain them :)

Volguus
Mar 3, 2009

Fruit Smoothies posted:

Not sure if this is the place for GWT discussion, but I figure I'll give it a whirl.

I'm new to Java, but familiar with pascal and PHP :cool:

I have a main google webapp class, and a secondary class, which handles all the XML getting. One function within this XML class has a callback which fires when the XML is received from the server.
I would like all this call-backing to be handled within the XML class, and for a function to be triggered within the main class when it's all done, so it can update the web GUI.
The XML get is async, so I can't feed the XML as a function result, and OO structure prevents the secondary class calling a function in primary. (right?)

In the world of windows GUI, the window would handle the event easily, but in this wilderness, I'm left stuck for ideas. Am I missing something blindingly obvious here?

I'm not sure I fully understand what you are trying to accomplish, but here is an example as to how to update a UI component after the server sends the answer back:

code:
 public class MainClass implements EntryPoint
{
   private TextBox textbox; //our UI component

   public void onModuleLoad()
   {
     //initialize the textBox and add it to the main panel
     .....
     //call the server
     MyServiceAsync service=(MyServiceAsync)GWT.create(MyService.class);
     service.getTextBoxData(new AsyncCallback<String>(){
           public void onFailure(Throwable ex){
             textbox.setText("Failed");
           }
           public void onSuccess(String result){
             textBox.setText(result);
           }
     });
   }
}
This code assumes you have defined the MyService service interface that has a method "public String getTextBoxData();"

As you can see, from an inner class you can access private members of the enclosing class.

If you want to have a completely separate class that handles the server communication, its possible to do it too. The MainClass would just have to expose a method "public void setTextBoxData(String text)" that would be called by the server communication class (that class would obviously need a pointer to the MainClass).

Does this help?

Volguus
Mar 3, 2009

Fruit Smoothies posted:

Unfortunately not. My issue was communicating between classes. I eventually found that an interface based on EventListener was the way forward.

This annoyingly comment-less code tried to give me an understanding. I eventually implemented it, almost verbatim, but I really don't see the need to have an array of listeners. Surely, just the one would do?

Thanks for your explanation and time. I apologise for my hideous explanation.

EDIT: And that is the worst way of doing a loop I have ever seen.

Yes, one listener would do, in your case.
But the code in there was providing a mechanism to have multiple listeners that can register themselves to be notified when an event occurs.
If you are 100% sure that you will never need more than 1 listener, you can take out the array, and instead have just a variable "private SignInListener listener" with a set and get.

Otherwise, you can leave the list of listeners in there, it won't hurt.

Volguus
Mar 3, 2009

Fruit Smoothies posted:

Yeah, I get that bit. I know how the XML class is created, I didn't know, since SignInListener doesn't appear to be a class, whether or not it needed a constructor. If it does, I couldn't see one.

The SignInListener is not a class. Is an interface. Explanation here: http://java.sun.com/docs/books/tutorial/java/concepts/interface.html

What you'll have to do is basically provide an implementation of that interface (can be the MainClass or an anonymous one) to the SecondaryXMLClass.

placid showed you the situation when the MainClass is the SignInListener implementation. Here is the anonymous class method. Such as:
code:
SecondaryXMLClass sXMLC = new SecondaryXMLClass();
sXMLC.addSignInListener(new SignInListener(){
 public void onSignInAttempt(boolean passwordOK)
    {
        //do whatever you want in here. 
    }

});
But, before I would go any further and cause myself a lot of grief, I would pick up a book to read (or at least read the entire tutorial that I provided the link to).

Volguus
Mar 3, 2009

Kaltag posted:


code:
public BufferedReader defaultIn = null; //binded to socket elsewhere
public BufferedReader passiveIn = null; //binded to socket elsewhere

				FileOutputStream out = new FileOutputStream(f);
				//IMPORTANT PART GOONS!
				//while(passiveIn.ready())
				for(int j = 0; j < Integer.parseInt(files.get(i).getSize()); j ++ )
				{
					out.write(passiveIn.read());
					//fileBytes[j] = (byte) passiveIn.read();
				} 
				//out.write(fileBytes, 0, fileBytes.length - 1);
				out.close();
				System.out.println("Done Transferring File");		


But, but....why?
Why not go the basic way of reading from a stream and writing into another? A way that works for any stream?

code:

OutputStream out=(whatever you want, FileOutputStream if you please)
InputStream in = (from wherever you got it from. network, file, memory....)

byte[] data=new byte[1024]; //this is how much data we're reading at once
int read=0;
while( (read=in.read(data))>=0)
{
  out.write(data,0,read);
}
out.close();
in.close();
and...its faster. I don't even want to look at your CPU reading byte after byte......
For local file transfer a higher buffer means faster transfer (ideally the HDD is the bottleneck not the CPU). For network...its tricky since the speeds are not anywhere close to HDD speeds.
usually 1k is just about enough.

Volguus
Mar 3, 2009

Capc posted:

I'm not sure exactly where I'd like to go from here. So far I've just enjoyed figuring out whatever terrible assignment they had us do for class, so I thought I'd keep going on my own this summer.

What's the next logical step? What are some subjects that might be helpful or fun to learn?

Why not take a look at Google Summer of Code ? I believe the registrations are closed, but you can look at all the projects that applied, and get ideas from their projects. Maybe you can find something fun.

Personally, for 4 days now I've been writing a yum file system (fuse, not in kernel). I found it fun. Would it be fun for you? Dunno.

Volguus
Mar 3, 2009

TRex EaterofCars posted:

Classes in the java.nio.channels package are even faster for reading/writing.

That is correct. But we must learn to walk before we can run.

Volguus
Mar 3, 2009

Contra Duck posted:



You'll need to run this in a separate thread though, or like Tulenian said the blocking operation will stop the rest of your program as well.

Be careful how do you do this. Usually the UI frameworks are not thread safe. That is: you should not update a UI component from a thread other than the tread who created it. This is true for most (if not all) of them.

Here is a tutorial for concurrency in Swing:
http://java.sun.com/docs/books/tutorial/uiswing/concurrency/index.html

Volguus
Mar 3, 2009

ashgromnies posted:

Yeah, it's not getting to the failed line... it's a really weird issue. I'm trying to get a local copy of the application running right now instead of debugging it on the server it's running on.

Working with Eclipse is such a pain in the rear end coming from a Perl/Python and vim background.
The reason is doesn't get to the failed line is because is throwing an exception.
most likely a SQLException.

You just need a good old try/catch/finally. In the catch block, the least you can do is :
code:
catch(SQLException ex){
ex.printStackTrace();
}
It does wonders for debugging. It may even tell you in plain english the answer to the most important question of them all: WHY?

Volguus
Mar 3, 2009

Gravity Pike posted:

Is there a simple way to create a list of references to objects? A rough sketch of what I'm trying to do...
code:
public class Goon {
   public Integer neckbeards;
   public String name = new String();
   public Boolean hasAClue;
   public Vector<Object> thingsICareAbout = new Vector<Object>(); 
  
   public static void main() {
   neckbeards = 1;
   name = "Gravity Pike";
   thingsICareAbout.add(neckbeards);
   neckbeards = 0;
   
   System.out.println(neckbeards.toString()+" vs "+thingsICareAbout.elementAt(0).toString());
   }
}
My output's going to be "1 vs 0", when I want it to be "0 vs 0" - I want the list to contain a reference to the variable, not the value of the variable. Is there a simple way to do this, without, say, creating a new class ThingsIMightCareAbout<U>, and having all of my variables be of this type? I'm a bit new to Java, and am perhaps thinking a bit too much as if I were coding in C++...

Yes there is.
You see, in Java every object is a pointer. That is, you only work with references, you never work with values. The only time you would ever work with values is when working with primitives (char,boolean,int,double,etc.)

Since Java 1.5 one fantastically useful and nice feature has been added to Java: autoboxing. However, for new users this is confusing.
For more information about autoboxing read: http://java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.html

Now, lets take your code and translate it (for you to see what you have done):

code:
public class Goon {
   public Integer neckbeards;
   public String name = new String();
   public Boolean hasAClue;
   public Vector<Object> thingsICareAbout = new Vector<Object>(); 
  
   public static void main() {
   neckbeards = new Integer(1);
   name = "Gravity Pike";
   thingsICareAbout.add(neckbeards);
   neckbeards = new Integer(0);
   
   System.out.println(neckbeards.toString()+" vs "+thingsICareAbout.elementAt(0).toString());
   }
}
So, you have basically created a new object everytime you do the Integer=int assignment. In Java 1.4 that would have not been permitted, now the compiler does the work for you.

The same is true with strings as well:
String a="a";
a="b";

The memory location of the first object is different from the memory location of the second one. These objects are ...special in Java. Strings have some operators overloaded, even though Java sdoesnt have operator overloading (concatenate strings with +, while == performs an .equals() ).
(One simple catch 22 situation: String extends Object, yet object has a public String toString() method.)

So in order to achieve your goal you should have your own object, with a setNeckbeards() method. Create one instance of that object, add it to the vector, set the neckbeards value to something else, and see it change everywhere that object is referenced.

Volguus
Mar 3, 2009

rjmccall posted:

There is no way of forming a reference to a local variable in Java.

What? What does the scope of a variable has to do with references ? What are you talking about?

MyNewObject obj=new MyNewObject();

obj is a reference. Global, local, static, final, whatever the hell you want. it is still a reference.

int i=1;
i will always point to the value of the variable, not to its location in memory. and in java you cannot even get that (like &i in C).

rjmccall posted:

Doing so is either unsafe (as in C++) or expensive (as in JavaScript or Smalltalk). Unfortunately, this does make certain kinds of metaprogramming difficult or impossible.

If it's an instance variable, you can use closures (anonymous classes) to do sortof what you want, except with gratuitous amounts of syntax:


I have no words for this...

Volguus
Mar 3, 2009

rjmccall posted:


GP wanted to know if you could create a reference to a variable, and the answer is no, you can't.


So, would you then please tell me what the following code does? What is "ref"?
code:
MyNewRef ref=new MyNewRef();
Here's a hint:

"ref" is a variable.
"ref" holds the reference to the MyNewRef object instance.
whether ref is local, private, public or whatever it doesn't change its status as a variable (you can change its value by saying: ref=new MyNewRef() this getting a new instances), and it will never change the fact that "ref" is just a reference.

If you can't see the absurdity of your statement...

Volguus
Mar 3, 2009

rjmccall posted:

It's exactly what you said: a variable that holds a reference to an object. What is wrong with you that you can't comprehend the difference between that and a variable that holds a reference to another variable? References are always references to something; Java allows you to create references to objects (indeed, it's the only way you can interact with objects), but not references to variables.

Here, look, this is a variable that holds a reference to another variable:

code:
int a;
int& b = a;
Note that this is C++ because you cannot express this in Java.
:doh: now I get it. You sir are confusing the "variable" concept with the "primitive" concept.

"ref" in my code is a variable
"a" in your code is a variable

ref is a reference to an object, a is a primitive.

Now i get your confusion. Please please, go back to CS101 and brush up on these very simple concepts. Come back after that and we'll talk.

In response to another question in this thread asked earlier:

In Java objects are passed by reference, primitives are passed by value. All the time and you cannot change this. This is something set in stone.
However, there is a set of objects that you cannot change their contents: String,Integer, Double,etc.
As such, even if you are passing a string object as a reference to a method, you cannot change its contents in that method and expect to see the new char array i the caller.
Thus:
code:
String a="a";
myMethod(a);
System.out.println(a);
...
public void myMethod(String a){
a="b";
} 
This code will print "a" to the console. In the myMethod method the string has been initialized with a new object (it became a reference to a different object).
The caller will never know that, it still has a reference to the old object.
The same is true for Integer. Doing this:
code:
Integer i;
i=1;
...
i=2;
is equivalent to doing this:
code:
Integer i;
i=new Integer(1);
...
i= new Integer(2);
So after the second initialization the reference to the first object (new Integer(1)) has been lost (unless kept in some other location, such as a list).

But...all of this babble is really just basic Java. Any book about the language (somewhat decent, not written by a VB programmer ) will tell you this and more.

Volguus
Mar 3, 2009

Brain Candy posted:

BZZZT. == foo is NOT .equals(foo) for Strings

You'd have to use .intern() or something similar for == to consistently work.

That is correct. However, "interning" is done automatically most of the time due to the following specifications:

# Literal strings within the same class (§8) in the same package (§7) represent references to the same String object (§4.3.1).
# Literal strings within different classes in the same package represent references to the same String object.
# Literal strings within different classes in different packages likewise represent references to the same String object.
# Strings computed by constant expressions (§15.28) are computed at compile time and then treated as if they were literals.
# Strings computed by concatenation at run time are newly created and therefore distinct.

For those who are wondering wtf this all means, run the following code:
code:
		String a="Hel"+"lo";
		String b="Hello";
		System.out.println(a==b);
		char[] c={'H','e','l','l','o'};
		String d="";
		for(int i=0;i<c.length;i++){
			d+=c[i];
		}
		System.out.println(d);
		System.out.println(d==b);
		System.out.println(d.intern()==b);
It will print:
true
Hello
false
true

Volguus
Mar 3, 2009

useless player posted:

I am trying to make a few modifications to a java program that was written by someone else. The previous programmer left her source code as well as the .class files. I can run the main .class file and the program starts, however when I recompile the main .java file without making any changes to it and try to run the program again, I encounter a NullPointerException for one of the lines in the main file. Replacing the main .class file that I compiled with the original one makes the program run again. The only explanation I can come up with is that the .class was compiled from a different source file than the one I was left with. Am I correct, or is there another explanation?

That is the most logical explanation. The original .class was compiled from a different source file than what you have.

Volguus
Mar 3, 2009

dealmaster posted:

Yeah I figured this was the route to go, but I'm having some weird behavior with the ScrollPane. When I put any text field, label, or anything else into the ScrollPane that I create, it immediately fills the whole thing up and won't let me resize it. Have you run into this before?

To get what you want, you'll need to create a custom scrollable component (extents JPanel probably).
You have a nice tutorial here: http://java.sun.com/docs/books/tutorial/uiswing/components/scrollpane.html#scrollable

Volguus
Mar 3, 2009

dealmaster posted:

For right now I've switched to a tabbed layout and it actually works a little better as far as organization is concerned, and it's alleviated the need for scrollbars, but I would still like them to be an option since I don't know what resolutions people will be using this application on.

As of right now an abstraction of the basic layout is this:

code:
           ----JPanel1----Tab 1 GUI stuff
           |
JTabbedPane----JPanel2----Tab 2 GUI stuff
           |
           ----JPanel3----Tab 3 GUI stuff
So ideally I'd like scrollbars to be optional on each of those JPanels, just in case someone using this application is running some stupidly small resolution. Do you know how to get JPanels to scroll vertically and horizontally?

Yes.
By creating a new class, that extends JPanel and implements Scrollable.
The tutorial that I've posted the link to provides the solution nicely.
And scrollbars will only appear when needed.

However...I'm not really sure why do you need scrollbars at all. I mean..the components should resize themselves when the application resizes. A very good layout to use is GridBagLayout. Complex but very powerful. If the users have a small resolution (you have to set a minimum supported, lets say 800x600), the components will just be smaller, but they should be proportional to a 1600x1200 resolution.

Volguus
Mar 3, 2009

geeves posted:

This is more an Eclipse setup question (and I come from an IntelliJ setup so Eclipse is very new to me)

Project tree is /svn/project/trunk/core/src/main/java/com/company/package/class

Project builds fine with Maven, and works properly when deployed; however Eclipse keeps throwing errors that: com.company.package is not valid and needs to be main.java.com.package.

It also does not recognize / reference other classes within the same package. Eclipse can see my Maven repo, but not this. :wtc:

I have the same project setup with IntelliJ and it's working fine.

Using Dynamic Web Project at the moment, but the others had similar results. Is this a setting or in the type of project it should be?
This sounds like Eclipse doesn't know what your root source directory is . In the project properties, set the source directory to that "main/java". Then the packages will follow from there( eclipse will properly see com.company.package as the package).

Volguus
Mar 3, 2009

dealmaster posted:

Yeah I tried using this layout, but I can't seem to figure out how to spread the combo boxes and text fields out how I'd like to. I tried using different anchor values and messing with the insets, but all the buttons, labels, etc. all end up clumping together. Even if I try to leave a bunch of blank space between two of them using the customize layout option in Netbeans, they don't actually move far away from each other, they're still stuck together.

you need to get away from that GUI editor. It's so easy to write a nice UI in java, that using a GUI editor will only slow you down.
Read this: http://java.sun.com/docs/books/tutorial/uiswing/layout/gridbag.html

It tells you how to use it, what all the arguments mean, etc.

Volguus
Mar 3, 2009

useless player posted:

Thanks for this. So it turns the project was in fact done using Intellij and that setupUI method was auto-generated by the IDE. I installed Intellij, put the files I had in a project and it looks like everything is working. I don't really get it, but I'm not complaining :).

Are you saying that Intellij is automatically generating a method (that is being called somewhere), and moving to a different IDE (or simple text editor) makes the code to not work anymore?

Well...that's -5 points for intellij off the bat right there. That's moronic.
The other -5 points of course come from the IntelliJ fans :colbert: .


One should be able to compile a java project (any project) using simple command line javac anytime he/she wishes.

Volguus
Mar 3, 2009

Mustach posted:

-cp, among many other things :effort:

Yep, I was totally arguing in favor of whatever you're talking about instead of arguing against "javac *.java is all you should ever need to do for any project!" I'll restate it without sarcasm: Beginners should be taught that it's okay to use tools like code generators and libraries that don't come with the JDK. Both of these things require understanding their project's build process! Amazing!

Well..if you read the guys post, it seems like the IDE was autogenerating a function ($$$setup$$$), probably at compile time.

This is hosed up, no matter how you look at it.
Wanna use a GUI builder? Go ahead. Have fun. But that GUI builder better generate code, not fancy shmancy stuff that will break the second you move away from that IDE/GUI builder.

Yes, you have to be able to use javac to compile a project. Would that be masochistic? Yes. But should you be able to do it, if you want to? You betcha.

Volguus
Mar 3, 2009

Fehler posted:

I would like to make a Java program extensible by allowing people to write their own classes (derived from a pre-defined class) which I would then load in my program. That way, I'm hoping to make it possible to add certain features without having to recompile the entire program, or even having access to the code.

So basically I'm looking for something like a DLL equivalent in Java. I think I read about something like this once, but I'm unsure on the details. Is there even such a thing in Java? How hard would it be to implement? What are some good starting points?

I've done something like this once for a program of mine.
Here is my approach to it (it can be done in a gazillion other ways, and half of them could be better than this):

- specify a directory where the plugin jars have to be located (for me it was plugins/)
- specify an information file that has to be in the .jar
in my case , i was looking for an xml file,named plugin.xml, that contained information about what kind of modifications that plugin wanted to make and what classes to load. Something like: Add menu item with text "X", on user click invoke action package1.package2.YourActionClass .
Of course, you can define whatever you want.

- Load up the class using a class loader. In my case I wrote my own, extending the JarClassLoader. The only reason I did that was that I looked in a specific directory for the .jar's, .jar's that normally would not be in the classpath

- Create an instance of the class, and invoke method Y



Hope this helps.

Volguus
Mar 3, 2009

HatfulOfHollow posted:

Can someone tell me what the performance hit of printing a stack trace is? I've got a piece of code that dumps a stack trace into the logs for roughly ~13 exceptions per minute all day long. Developers want justification that there is a performance issue because apparently 20k exceptions per day isn't a good enough reason to fix the code. I wrote up some bullshit about how the machine is I/O bound so constantly writing to disk is worse performance than whatever in-memory operation usually takes place when the code succeeds. But I'm looking for specific information like printing a thread dump pausing processing while the trace is built, or interfering with garbage collection. Something more concrete than what I've pulled out of my rear end. If there isn't anything I guess I need to go with "Why are we tolerating code that throws so many exceptions? Who designed this crap?"

I am not aware of any "special" operations that may occur when a program requests a stack dump. Those who know more than I do are welcome to bring their arguments to the table.

But...just look at the drat IO. the logs for christ sake. 20k exeptions per day are useless. Nobody will ever look through them all and try to figure out a problem. That's where...the real problems will come up and they will be lost in the mountain of exceptions that are not that important.

Exceptions ...are just that: EXCEPTIONS. Not the rule. If the programmers made that the rule...it's bad.

These reasons alone should be sufficient. If they are not and you need to come up with:" but the earth spins slower when you throw that many exceptions" argument, I think you have bigger problems on your hands than just a mountain of exceptions .

Volguus
Mar 3, 2009

snoot posted:

I have a web service that calls a third party Java API that requires an absolute path to a configuration file for it to function.

How do I include the config file in the web service 'war', then find the absolute path to that file?

I'm using Netbeans as an IDE and GlassFish to run the web service.

I guess this is fairly straight forward? I usually work in C#, and don't know where to look to figure out how to do this kind of thing in Java. Any pointers would be greatly appreciated.

Short answer: you don't.

Long answer:
Depending on your web application server, the war file may or may not be unzipped while being deployed.

The safest way to do this is as follows:
InputStream in=getClass().getResourceAsStream("path to your file");
create a new file in the tmp directory (System.getProperty("java.io.tmpdir")).
Write into that file the contents of the "in" stream.
pass the full path to that file to the library. let it do its thing, delete the file.

"path to your file" is relative to your classpath.
if the file is in WEB-INF/classes then asking for: /myproperties.file should work just fine.
if it's in a package... just prepend the package path to the filename (/com/mycompany/myapp/file.properties)

Hope this helps.


short edit: some libraries (spring for example) know to get a properties file in the classpath, this library my know that as well. For spring I specify the xml file path as: classpath:/application-context.xml where the file is located in the war file in WEB-INF/classes

Volguus fucked around with this message at 22:15 on Aug 27, 2009

Volguus
Mar 3, 2009
As stated above: using interfaces.

don't give access to the actual collection (if you want to protect a collection), but instead provide an interface, with getObjectAt(index) type of functions. Or...getIterator(), etc.
The code will not become much more complicated:
code:
 public interface ListHandler{
   public Object getObjectAt(int index);
   public Iterator getIterator();
 }

 public class ArrayListHandler implements ListHandler{
  ...here do your stuff+ implement the 2 methods
 }

 ...
Then, whenever you need to pass the ArrayListHandler to a method, or return it from some method, don't pass the object but the interface.
Such as:

code:
 public class MyFactory{
  public ListHandler getMyListHandler(){
  ArrayListHandler handler=new ArrayListHandler();
   handler.addObject(new Integer(1));
   handler.addObject(new Integer(2));
   return handler;
  }
 }
As you can see, whoever calls the getMyListHandler() method will only get the interface, and as such, only access to the provided read-only methods.

Of course, what you cannot do, is prevent that person from casting to the implementation. That...you cannot help it. But they will get burned when you change the implementation of the same interface :).

Volguus
Mar 3, 2009
I'm not really sure how to answer this, since they give in there example code and explanation about how it all works out. It can't be better, imo.

What exactly do you try to accomplish?

the example clearly gives you:

- How to create a popup menu and add items to it.
- How to display the said popup menu when the user right-clicks on a component (in that example, both "output" and "menuBar" got the popupListener).

I saw from your code that you are creating the popup menu. and added items to it. And you have an actionlistener created, but it doesn't seem to do anything (no showing the menu). Nor do you seem to add said listener to a component for it to be actually called.
So, i cant really say what's missing unless you'll tell more.

Edit:
ooo, so its showing up, but on both clicks. I see now.
The "e.isPopupTrigger()" line is essential in this case.

Volguus
Mar 3, 2009

Kaltag posted:

That's all I needed to hear.

popUp.setUI(new BasicPopupMenuUI()); sets the windows look and feel, causing isPopUpTrigger to be true only when there is a right click. I only had to modify my actionlistener that added to my menuItem to include the line

code:
if(e.isPopupTrigger())
    popUp.show(e.getComponent(), e.getX(), e.getY());
and it works just great.

I'm guessing unless you set the UI to be new BasicPopupMenuUI() then e.isPopupTrigger will always be true, by default.

Thanks rhag!

That should not be the case. You should not have to set the UI, since that should be set by the current Look&Feel.
You do have a line (at the beggining of your main function, before creating & showing your main frame window), like this:
UIManager.setLookAndFeel("some L&F class")?

Usually, I just use the platform's L&F, and that can be accomplished easily by:
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); Or, just use the Metal L&F :UIManager.getCrossPlatformLookAndFeelClassName().

I don't remember ever having e.isPopupTrigger() being true on both mouse buttons. I'm guessing that happens in your case because you didn't set the UI. I hope.

Anyhow, you're welcome.

Volguus
Mar 3, 2009

Anunnaki posted:

I seem to be having a lot of trouble just trying to use 64-bit Java. My browsers don't detect it, I had to scour the internet to find 64-bit installations of IDEs, etc. Is it just not worth it? I mean, there have to be some developers who make 64-bit Java programs..?

Umm....is this a troll?
In the 0.01% chance that it isn't, here are some answers:

Eclipse has a jdk x86_64 version. Dunno about other IDEs.
Nobody writes 64-bit Java programs . The...concept doesn't really make sense. You write a java program that program will run on the i586 and 64-bit JVMs. On any OS.
Browsers: the browser has to be a 64 bit browser with a 64-bit java plugin to be able to run applets using the 64-bit JRE. I don't think firefox comes in the 64-bit flavour. IE does i think, never really cared.

Your java program won't ever really know if its running in a 64-bit JRE, nor should it care.

Volguus
Mar 3, 2009

HFX posted:

The same is true for many interpreted languages which use a jit interpreter. It is also why benchmarks can be nearly meaningless when comparing Java to statically compiled languages without having a sufficiently long runtime.

Anyway, the biggest difference between the two virtual machines (32 and 64) is the maximum amount of addressable RAM. 32bit has an upper limit of something around ~1200MB (found by testing). I'm not sure of the limit on the 64bit version at the moment, as 4 gigs was good enough.

A 32 bit program (any 32 bit program) cannot access more than 4GB of ram (architecture limitations). In real-life 2GB is the max that normal Windows allows (2GB for the kernel, 2GB for apps). That is... the normal Windows. With PAE it can access more. You have found 1200MB to be the limit because of the other things the JVM needs RAM for (loading the classes for example, that Perm space).

In a 64 bit program, the limitation is much much higher: 2^64 = huge number. On MSDN (http://msdn.microsoft.com/en-us/library/aa366778%28VS.85%29.aspx) MS says that the limit is 8TB.

So...that should be enough or everybody, shouldn't it?

Anyhow, the only case you would have to care about that, if your Java program is using JNI. Then you would have to make libraries available for whatever OS/Architecture you intend to support:
A 64 bit dll for 64 bit windows with a 64 bit JVM
A 32 bit dll for 64/32 bit windows with a 32 bit JVM
A 64 bit .so for 64 bit Linux with a 64 bit JVM
...
and so on and so forth for every Unix and JVM under the sun.

But the Java program would not change. the JNI call will always be the same, just the actual native code may be different.

Volguus
Mar 3, 2009

Vandorin posted:

Ah thanks. Now I've just got to figure out how to add in color for the other 2 thirds. Would I just mess with the for loop, making i > s and i == s?

Depends what do you want out of the image.
One way would be to go from 0 to s, inside the for do int m=i%3;. Now, m can have 3 possible values: 0,1,2. If m=0 color it one way, if it equals 1 another way and if it equals 2 another way.

Another alternative would be to go from 0 to s, but check the values that i has:
if(i<s/3) do this,
if(i>=s/3 && i<2*s/3) do that,
if(i>2*s/3) do another thing.

Or 3 for loops.
The possibilities are endless :).

Volguus
Mar 3, 2009

Vandorin posted:

I tried the alternative code you mentioned (because I understand it better) but for some reason only the first third is getting filled. Here's what I've typed so far:
code:
  public void secondThird()
     {
        // Get the pixels
       Pixel[] thePixels = this.getPixels();
       int len = thePixels.length;
       int count = 0;
       
       // For loop to make sure it's inbetween the first third, and the last third.
         
       for( int i = 0; i >= len / 3 && i < 2 * len / 3; i++ )
      {
           thePixels[i].setBlue(2);
      }
   
    }
I made sure to put the secondThird method in my main program, so I can't figure out why it's not working. :(


Try this:
code:
//This will set all the pixels in the middle (between first third and the last third)
  for( int i = (len / 3);  i < (2 * len / 3); i++ )
      {
           thePixels[i].setBlue(2);
      }
The brackets are not really needed, but it makes the code clearer a tiny little bit.
So, for let's say: len=6.

i starts at 2;
runs until it gets to 2*6/3=4;
That means, pixels 2 and 3 (in the zero based array) will get their blue color set to 2.
To get the last third (4 and 5 pixels) you do this:
code:
  for( int i = (2 * len / 3);  i < len; i++ )
      {
           thePixels[i].setBlue(2);
      }
The reason your code didn't work is this:
Lets say len =6;
i starts at 0;

The for loop as you wrote it runs until (0 >= 6/ 3 && 0 < 2 * 6/ 3)==false

as you can see 0>=2 is false ,thus the entire expression is false .

I assume you are a student and this is some school project. I hope that you're not a developer that somebody pays to write code. right?

Volguus
Mar 3, 2009

zootm posted:

This was my impression about the same time as well, although POI development seems to have picked up since then so it might actually be the better option now. I remember meaning to look at it again but I've not had any reason to interoperate Java and Office since then.

I have personally used Apache POI (http://poi.apache.org/) for both writing and reading excel files (last time I used them was 6 months ago) , and I was very pleased with the result.
Haven't used JExcel yet, but I will certainly give it a try next time I have to produce an excel report from a java application (being it web or desktop).

Adbot
ADBOT LOVES YOU

Volguus
Mar 3, 2009

fletcher posted:

Thanks to both of you guys for the help, but I think I'm gonna have to go with epswing's solution for this one! Thank you!

epswing's suggestion is perfect, if the HTML you get to parse is properly formatted.

Another suggestion would be to use a HTML parser (as opposed to an XML one), such as the one in the JDK : http://java.sun.com/javase/7/docs/api/javax/swing/text/html/parser/Parser.html
That one is a bit more forgiving.

Or a 3rd party library, like http://htmlparser.sourceforge.net/

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