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
Flobbster
Feb 17, 2005

"Cadet Kirk, after the way you cheated on the Kobayashi Maru test I oughta punch you in tha face!"

zootm posted:

A lot of thought seems to have gone into making enums "work right".

If only they could have applied the same amount of thought to other parts of Java, like generics.

Adbot
ADBOT LOVES YOU

Fly
Nov 3, 2002

moral compass

Flobbster posted:

If only they could have applied the same amount of thought to other parts of Java, like generics.
Generics are okay-ish if a bit lame.

I don't like the failied auto-unboxing of nulls though. It seems that if the default value of an Integer is null, and the default value of int is zero, then auto-unboxing a null Integer reference should return zero instead of allow for a new type of semi-obscure NullPointerException bug. It just seems unexpected for the default value not to unbox to the default value.

FindBugs can help location those.

Mill Town
Apr 17, 2006

Fly posted:

Generics are okay-ish if a bit lame.

I don't like the failied auto-unboxing of nulls though. It seems that if the default value of an Integer is null, and the default value of int is zero, then auto-unboxing a null Integer reference should return zero instead of allow for a new type of semi-obscure NullPointerException bug. It just seems unexpected for the default value not to unbox to the default value.

FindBugs can help location those.

Null isn't the default value of an Integer, it's the default value of a reference to an Integer, which is a different thing. Integer doesn't have a default value because it doesn't have a default parameterless constructor.

zootm
Aug 8, 2006

We used to be better friends.

Flobbster posted:

If only they could have applied the same amount of thought to other parts of Java, like generics.
Generics makes sense from the point of view that the developers of that were not allowed to change bytecode.

Of course that was a stupid restriction, which has saddled us with the pain we have now.

necrobobsledder
Mar 21, 2005
Lay down your soul to the gods rock 'n roll
Nap Ghost
The funny part is that the bytecode changed in other areas anyway, which means they might as well have let them change it.

I've always thought the worst thing about Java isn't the language but the JSR and JCP.

Fly
Nov 3, 2002

moral compass

Mill Town posted:

Null isn't the default value of an Integer, it's the default value of a reference to an Integer, which is a different thing. Integer doesn't have a default value because it doesn't have a default parameterless constructor.
That's a good point. The failure on auto-unboxing the default reference value still introduces a new type of bug that I would rather not have to deal with.

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

Fly posted:

That's a good point. The failure on auto-unboxing the default reference value still introduces a new type of bug that I would rather not have to deal with.

I simply stopped using primitives due to this. I didn't want the issues to ever come up again. I almost never use arrays any more either.

8ender
Sep 24, 2003

clown is watching you sleep

necrobobsledder posted:

I've always thought the worst thing about Java isn't the language but the JSR and JCP.

I agree, and the entire web part is a mess. The worst part is that when you start out doing web development in Java everything you read is like "Hey JSF + EJB is the reference, its the way to go!" so you start learning and developing in JSF only to find out its a huge clunky piece of poo poo.

Then 8 months in you realize that all the cool kids are using Struts2 or Spring or anything but JSF and pairing it with Hibernate or iBatis and you feel like a big dick for wasting a ton of time.

amr
Feb 28, 2005
I love boxes of toast
I'm building the GUI for a program I'm working on and I've hit a bit of a problem.

My GUI is arranged in the following way: a 'main' JFrame that is always open, a JTree in the JFrame (on the left), and a large JPanel taking up the rest of the JFrame. I'm swapping panels in and out of that JPanel, depending on what the user wants to do.

The problem I have is I'm not sure how to assemble my JTree and for it to load new instances of my the JPanels. Any ideas?

Edit: I can do the actual swapping, I've written a setPanel() method for the main window. I basically need to call setPanel(new NameOfNewPanel()); when a user clicks on an item in the JTree.

1337JiveTurkey
Feb 17, 2005

amr posted:

I'm building the GUI for a program I'm working on and I've hit a bit of a problem.

My GUI is arranged in the following way: a 'main' JFrame that is always open, a JTree in the JFrame (on the left), and a large JPanel taking up the rest of the JFrame. I'm swapping panels in and out of that JPanel, depending on what the user wants to do.

The problem I have is I'm not sure how to assemble my JTree and for it to load new instances of my the JPanels. Any ideas?

Edit: I can do the actual swapping, I've written a setPanel() method for the main window. I basically need to call setPanel(new NameOfNewPanel()); when a user clicks on an item in the JTree.

CardLayout on the right hand side to swap things, then put a TreeSelectionListener on the tree to be informed whenever the user picks something different. Usually you'd make or extend your own tree model to store the information about the editor that should be shown for that tree node.

amr
Feb 28, 2005
I love boxes of toast
That's what I'm doing currently. CardLayout to swap the panels, and extending my own tree, the problem is I'm not sure how to store nodes in the JTree and then how I should load the correct panel. Currently I've got a big switch statement and I'm swapping based on the node's toString() (not the best idea, I know, that's what I'm wanting to change it)

Ferg
May 6, 2007

Lipstick Apathy
So I haven't touched Java since college and I'm diving back in for an Android project that is coming up for work. Being that this is my first time doing legit Java work (and since Java 1.4) can anybody explain to me the proper naming conventions for packages?

Here's my setup: I've got the Android app frontend, a set of classes that define the backend logic (interfacing with a web service), and then a series of utilities. Ballparking it, I figured I'd use this convention:

com.myapp.frontend
com.myapp.backend
com.myapp.utilities

Azerban
Oct 28, 2003



I've got an applet that needs to connect to a MYSQL database that's sitting behind a firewall, maybe two. What is the best, and/or easiest, way to get this done?

e: for reference, the method the network admin. suggested was to use a set of PHP pages to query the database indirectly, but I'm not completely sure how that would work?

Azerban fucked around with this message at 17:14 on Feb 11, 2010

lamentable dustman
Apr 13, 2007

🏆🏆🏆

Ferg posted:

So I haven't touched Java since college and I'm diving back in for an Android project that is coming up for work. Being that this is my first time doing legit Java work (and since Java 1.4) can anybody explain to me the proper naming conventions for packages?

Here's my setup: I've got the Android app frontend, a set of classes that define the backend logic (interfacing with a web service), and then a series of utilities. Ballparking it, I figured I'd use this convention:

com.myapp.frontend
com.myapp.backend
com.myapp.utilities

doesn't really matter as long as it meets your companies guidelines. Just make sure it is logically placed

lamentable dustman
Apr 13, 2007

🏆🏆🏆

Azerban posted:

I've got an applet that needs to connect to a MYSQL database that's sitting behind a firewall, maybe two. What is the best, and/or easiest, way to get this done?

e: for reference, the method the network admin. suggested was to use a set of PHP pages to query the database indirectly, but I'm not completely sure how that would work?

Is the server that is serving the applet able to reach the database? If so you can use a servlet to do connect to the database. If they aren't on the same server then the applet has to be signed.

In the applet you would do something similar to:
code:
URL url = new URL(pathToServlet);
URLConnection conn = url.openConnection();
//use HttpsURLConnection for a https connection
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Content-Type","application/x-java-serialized-object");


//TO servlet
OutputStream out = conn.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(out);

oos.writeObject(yourObject);
//this would be parameters for your query


//recieve object back from servlet
InputStream instr = conn.getInputStream();
ObjectInputStream inFromServelt = new ObjectInputStream(instr);
Object obj = inFromServlet.readObject();


//clear connection
oos.flush();
oos.close();
out.flush();
out.close();
inFromServlet.close();
instr.close();
Servlet code would look like this;
code:
//from applet
InputStream instr = request.getInputStream();
ObjectInputStream inFromApplet = new ObjectInputStream(instr);
Object obj = inFromApplet.readObject();


//and back to object
response.setContentType("application/x-java-serialized-object");
OutputStream out = response.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(out)
oos.writeObject(rtnObject);

//close connection
oos.flush();
oos.close();
out.flush();
out.close();
instr.close();
inFromApplet.close();
probably some errors in there as I had to hand type it from my secure machine


e: A couple things, you probably need a time out in the applet in case the servlet is down as it won't do anything till it gets a response from the servlet. If you need to pass a primitive to the servlet just use one of the wrapper classes. You can also only pass serializable objects back and forth.

lamentable dustman fucked around with this message at 18:17 on Feb 11, 2010

Kanen
Aug 20, 2003
Okay, I give up. I'm not sure if my problem belongs in this thread or should be in its own thread (the preview looks long). Here is my situation:

I am hosting my application in Tomcat 6 in a windows XP environment. I am connecting to a MySQL database (5.1.39) via JDBC (mysql-connector-java-5.1.11-bin.jar) and pooling it through JNDI datasource explained here: http://tomcat.apache.org/tomcat-6.0-doc/jndi-resources-howto.html. I have the needed jar files in my tomcat/lib folder.

I am having a connection issue where a db connection closes and it seems to close all db connections. This is causing slightly longer running ResultSets from closing in the middle of their reading, but only when the queries are executed at practically the same time (I am using two windows and submitting a form at the same time). Now, I'm sure what is wrong is something simple and I have just overlooked it or don't know what exactly to google. Any help would be greatly appreciated. Below is some code examples:

Connection Management:
code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

public class AppConnection {
	
	private DataSource dataSource = null;
	public void StartDataSource(){
		try{
			Context init = new InitialContext();
			Context ctx = (Context) init.lookup("java:comp/env");
			dataSource = (DataSource) ctx.lookup("jdbc/ROOT");
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}
	
	public void closeCon(Connection con){
		try{
			if(con != null){
				if(!con.isClosed()){
					if(AppInfo.DEBUG) System.out.println(CurrentDate.getInstance().getDateTime() +"CONNECTION CLOSED");
					con.close();
					con = null;
				}
			}
		}catch (Exception ex) {
			ex.printStackTrace();
		}
	}
	
	public void closeStmt(PreparedStatement stmt){
		try{
			if(stmt != null){
				stmt.close();
				stmt = null;
			}
		
		}catch (Exception ex) {
			ex.printStackTrace();
		}
	}
	
	public void closeStmt(PreparedStatement stmt, ResultSet rs){
		try{
			if(rs != null){
				rs.close();
				rs = null;
			}
		}catch (Exception ex){
			System.out.println("Issue Closing ResultSet");
		}
		try{
			if(stmt != null){
				stmt.close();
				stmt = null;
			}
		
		}catch (Exception ex) {
			ex.printStackTrace();
		}
	}
	
	 public Connection checkCon(Connection con){
		 Connection conNew = null;
			try{
				StartDataSource();
				if(con != null){
					if(!con.isClosed()){
						conNew = con;
					}else{
						if(AppInfo.DEBUG) System.out.println(CurrentDate.getInstance().getDateTime() +"CONNECTION CREATED");
						conNew = dataSource.getConnection();
					}
				}else{
					if(AppInfo.DEBUG) System.out.println(CurrentDate.getInstance().getDateTime() +"CONNECTION CREATED");
					conNew = dataSource.getConnection();
				}
				
			}catch(Exception e){
				e.printStackTrace();
			}
			return conNew;
		}
context.xml in META-INF
code:
<Context path="/ROOT" docBase="ROOT"
        debug="5" reloadable="true" crossContext="true">

 <Resource name="jdbc/ROOT" auth="Container" initialSize="10" maxIdle="20" maxActive="50" maxWait="5000"
  type="javax.sql.DataSource" username="user" password="password" 
  removeAbandoned="true" removeAbandonedTimeout="30" logAbandoned="true"  driverClassName="com.mysql.jdbc.Driver"
   url="jdbc:mysql://localhost/databasename?autoReconnectForPools=true" validationQuery = "select 1"/>
</Context>
Note: I have tried with autoReconnect=true after db url, and various combos of.

Addition to web.xml:
code:
<resource-ref>
  <description>
    datasource thing
  </description>
  <res-ref-name>
    jdbc/Root
  </res-ref-name>
  <res-type>
    javax.sql.DataSource
  </res-type>
  <res-auth>
    Container
  </res-auth>
</resource-ref>
Here is the connection being called:
code:
	public ArrayList reportResults(SearchVO search){
		ArrayList list = new ArrayList();
		
		String WhereStmt = "";
		boolean First = true;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try{
			APPartsConn = checkCon(null);
			WhereStmt = whereStmt(search);
			
			if(WhereStmt.length() > 0)
			{
				WhereStmt = " and " + WhereStmt;
				
				stmt = APPartsConn.prepareStatement("a functioning SQL Command " +
						WhereStmt + " order by p.partnumber");
				if(AppInfo.DEBUG) System.out.println(CurrentDate.getInstance().getDateTime() +stmt);
				rs = stmt.executeQuery();
				
				while(rs.next()){
					InventoryVO inventory = new InventoryVO();
					
					inventory.setConsignorPartNumber(rs.getString(3));
					inventory.setConditionName(rs.getString(5));
					inventory.setStatus(rs.getString(6));
					inventory.setQuantity(rs.getInt(7));
					inventory.setCostPerQuantity(rs.getDouble(9));
					inventory.setEbayItem(rs.getBoolean(10));
					
					...//more populations run below
					
					list.add(inventory);
				}
				closeStmt(stmt, rs);
			}
			
			
		
		}catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			closeCon(APPartsConn);
		}
		
		return list;
	}
Now, frequently I pass the connection around to other functions in other classes to make things run faster, for example:
code:
public InventoryVO populate(int ID, Connection con){
		InventoryVO bean = new InventoryVO();
		
		try{
					
			
			APPartsConn = checkCon(con);
			PreparedStatement stmt = APPartsConn.prepareStatement("select * from " + Table + " where " + PrimaryKey + " = ?");
			stmt.setInt(1, ID);
			
			ResultSet rs = stmt.executeQuery();
			
			if(rs.next()){
				bean = new InventoryVO(
						//populate base stuff
						);			
				bean.setPartCatalog(PartCatalog.getInstance().populateJustPart(bean.getPartCatalogID(), "INV",APPartsConn));
				bean.setLocation(Location.getInstance().populateJustLocation(bean.getLocationID(), APPartsConn));
				bean.setLot(Lot.getInstance().populateJustLot(bean.getLotID(), APPartsConn));
			}
			
			
		closeStmt(stmt, rs);
		}catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			if(con == null)
			closeCon(APPartsConn);
		}
The problem is, when I run two searches at the same time, one of them will die with the following error buried in the logs (starting with each different connection being created:
code:
2010-02-11 13:13:48CONNECTION CREATED
2010-02-11 13:13:48com.mysql.jdbc.JDBC4PreparedStatement@1efa490: //SQL stmt
2010-02-11 13:13:48CONNECTION CREATED
2010-02-11 13:13:48com.mysql.jdbc.JDBC4PreparedStatement@4e8edc: //SQL stmt
2010-02-11 13:13:48com.mysql.jdbc.JDBC4PreparedStatement@e62121: //SQL stmt
//trimmed some crap
2010-02-11 13:13:48CONNECTION CLOSED
java.sql.SQLException: Operation not allowed after ResultSet closed
	at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1072)
	at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:986)
	at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:981)
	at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:926)
	at com.mysql.jdbc.ResultSetImpl.checkClosed(ResultSetImpl.java:794)
	at com.mysql.jdbc.ResultSetImpl.findColumn(ResultSetImpl.java:1105)
	at com.mysql.jdbc.ResultSetImpl.getInt(ResultSetImpl.java:2813)
	at org.apache.tomcat.dbcp.dbcp.DelegatingResultSet.getInt(DelegatingResultSet.java:237)
	at com.chipsemi.parts.partcatalog.PartCatalog.populateJustPart(PartCatalog.java:273)
...blah blah blah
This happens when one of the connections closes while a ResultSet from a different browser is still running. When looking at my mysql processlist, it is obvious that two connections were used, one to process each browser since the sleep times are in sync. But I have no idea why the .close() is killing all connections. There has to be some easy way to prevent this, but all of my trial and errors result in the same problem and as I said before I have had no manner of luck with google. Any help would be awesome. Thanks in advance!

Kanen fucked around with this message at 21:07 on Feb 11, 2010

Fly
Nov 3, 2002

moral compass
I don't see APPartsConn defined anywhere. If it's shared by multiple threads of execution, which it may well be since the scope of APPartsConn is not evident from the code you posted, then that would be the problem.

Kanen
Aug 20, 2003

Fly posted:

I don't see APPartsConn defined anywhere. If it's shared by multiple threads of execution, which it may well be since the scope of APPartsConn is not evident from the code you posted, then that would be the problem.

Sorry, it is defined at the top of the class:

code:
private static Connection APPartsConn = null;
Does it need to be defined within the function itself? I haven't tried that.

Fly
Nov 3, 2002

moral compass

Kanen posted:

Sorry, it is defined at the top of the class:

code:
private static Connection APPartsConn = null;
Does it need to be defined within the function itself? I haven't tried that.
Yes, it does. Each thread needs its own Connection or you may be getting who-knows-what data mixups using a static (global) Connection reference.

edit: rephrased

Fly fucked around with this message at 23:59 on Feb 11, 2010

Kanen
Aug 20, 2003

Fly posted:

Yes, it does. Each thread needs its own Connection. You're getting who-knows-what data mixups using a global Connection.

I just ran a few tests, that seems to have fixed it. I knew it was something simple I was overlooking. Thanks a ton.

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.
If you need speed, why not use a DB Connection Pool? It'll handle all the thread safety issues you're having now plus give you better query latency.

Fly
Nov 3, 2002

moral compass

TRex EaterofCars posted:

If you need speed, why not use a DB Connection Pool? It'll handle all the thread safety issues you're having now plus give you better query latency.
I do not think a connection pool would solve the thread safety issue above, but it might be less likely to lead one to want a singleton connection.

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

Fly posted:

I do not think a connection pool would solve the thread safety issue above, but it might be less likely to lead one to want a singleton connection.

You're right. However, I do think that having to allocate the pool then having the connection manager act as your singleton would help in making it more clear how to handle database connections. Maybe I'm wrong.

Fly
Nov 3, 2002

moral compass

TRex EaterofCars posted:

You're right. However, I do think that having to allocate the pool then having the connection manager act as your singleton would help in making it more clear how to handle database connections. Maybe I'm wrong.
I think you're right. :)

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
Looking for a way to generate some charts in Java and output to an image. JFreeChart looks pretty sweet, anything else I should check out before diving in?

lamentable dustman
Apr 13, 2007

🏆🏆🏆

fletcher posted:

Looking for a way to generate some charts in Java and output to an image. JFree looks pretty sweet, anything else I should check out before diving in?

Used it before, it works really well but the documentation sucks and is built around buying his book. Probably worth it but if you're cheap like me (or rather my company...) use a recompiled to look around the source of his demo app to learn alot

lamentable dustman fucked around with this message at 02:47 on Feb 12, 2010

1337JiveTurkey
Feb 17, 2005

amr posted:

That's what I'm doing currently. CardLayout to swap the panels, and extending my own tree, the problem is I'm not sure how to store nodes in the JTree and then how I should load the correct panel. Currently I've got a big switch statement and I'm swapping based on the node's toString() (not the best idea, I know, that's what I'm wanting to change it)

Swing is MVC-oriented, so the idea is that your data should either implement the TreeModel or TreeNode interfaces or have that as a front end that ultimately manipulates them. Then it's not really a question of how you store the nodes because then the JTree is just a window (the View) onto your Model. The tree then by default displays the toString() of the nodes themselves and you can have all the data you need inside of the nodes. To pick what to display there's a few ways.

The most straightforward method of just having a method that gets the panel itself on the node has the problem that it sticks a dependency on your View in the Model when generally it should always be in the other direction. Using a map of node classes to right hand panels could also work. The selection listener would then get the selected node and look up its class to find the correct right hand panel, then pass the node to the panel in some initialize method. That can be made as simple or as complex as you like.

Parantumaton
Jan 29, 2009


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

fletcher posted:

Looking for a way to generate some charts in Java and output to an image. JFreeChart looks pretty sweet, anything else I should check out before diving in?

Is pure image a necessity or are you doing a Web UI?

Fly
Nov 3, 2002

moral compass

fletcher posted:

Looking for a way to generate some charts in Java and output to an image. JFreeChart looks pretty sweet, anything else I should check out before diving in?
We've been using http://jcharts.sourceforge.net/ for nearly a decade. It seems to work quite well.

necrobobsledder
Mar 21, 2005
Lay down your soul to the gods rock 'n roll
Nap Ghost

fletcher posted:

Looking for a way to generate some charts in Java and output to an image. JFreeChart looks pretty sweet, anything else I should check out before diving in?
It doesn't actually fit your requirements, but if it has anything to do with showing a chart on a web page, you should probably look at Google Charts. The caveat is that it does require the user have some access to the Internet, so it breaks if they're in, say, a closed off datacenter.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Parantumaton posted:

Is pure image a necessity or are you doing a Web UI?

Just need a static image for this one. Already using Open Flash Chart for the web stuff.

necrobobsledder posted:

It doesn't actually fit your requirements, but if it has anything to do with showing a chart on a web page, you should probably look at Google Charts. The caveat is that it does require the user have some access to the Internet, so it breaks if they're in, say, a closed off datacenter.

That's what I used for the proof of concept. Google Charts are pretty neat, but it seems a bit limited in what you can do. Plus passing everything into the URL is a bit of a pain.

Fly posted:

We've been using http://jcharts.sourceforge.net/ for nearly a decade. It seems to work quite well.

I saw that one but I wasn't really impressed with their samples. They look so...Excel 97.

I've been playing around some more with JFreeChart. The amount of customization you can do seems to be very thorough. I think this might be the right engine.

JFreeChart + data URI scheme = :cool:

fletcher fucked around with this message at 00:04 on Feb 13, 2010

epswing
Nov 4, 2003

Soiled Meat

fletcher posted:

JFreeChart + data URI scheme = :cool:

This is so you don't have to save the image to a web-accessible folder? You just send the contents as base64 and the browser renders it? Neato.

Guess the downside is you have to generate the image every time, but I suppose that's fine if it changes often enough.

Fly
Nov 3, 2002

moral compass

fletcher posted:

I saw that one but I wasn't really impressed with their samples. They look so...Excel 97.
I'll check out JFreeChart when it comes time to redo our current charts.

amr
Feb 28, 2005
I love boxes of toast

1337JiveTurkey posted:

Swing is MVC-oriented, *snip* That can be made as simple or as complex as you like.

Thanks for your advice, although some of that went way over my head :P This is my first time actually doing a proper user interface for my program. I'm still not quite sure how to do it. I was thinking of trying to use reflection or having a static getInstance() method. Do you know of any material I can read so I know what I'm doing? Cheers

1337JiveTurkey
Feb 17, 2005

amr posted:

Thanks for your advice, although some of that went way over my head :P This is my first time actually doing a proper user interface for my program. I'm still not quite sure how to do it. I was thinking of trying to use reflection or having a static getInstance() method. Do you know of any material I can read so I know what I'm doing? Cheers

These two articles give a 10,000 foot overview of Swing and MVC:
http://en.wikipedia.org/wiki/Swing_(Java)
http://en.wikipedia.org/wiki/Model%96view%96controller

Here's the standard tutorial which covers how to use Swing in depth:
http://java.sun.com/docs/books/tutorial/uiswing/

To answer your question, it really depends on what your requirements are. For the one-off utilities that I've worked on, just slapping a getPanel() method on the node itself is often perfectly adequate even if it tightly couples some aspects of the program. For the flagship application I work on, it's a full-fledged subsystem with dozens of pluggable editors available for various combinations of nodes along with stuff like dynamic per-seat licensing. If I were to remove the huge amount of legacy cruft on it and pare it down to its core, that'd be basically the controller for the right hand panel asking all of the editors "can you edit this set of nodes?" and then adding a tab for each one that returns true. It works well with plugins and is pretty much instantaneous even with well over 100 different possible tabs since they're just looking at the number of nodes as well as their class.

Coredump
Dec 1, 2002

Is there a way to write a for loop that will make create new arraylist with the number fed into? I'm trying something like this:

code:
 for (int i = 0; i < numberofarrys; i++)
  {
   ArrayList<String> al[i] = new ArrayList<String>();
}
I was hoping the [i] would be able to make al1 al2 al3 etc. So far it doesn't work. What's the best way to do that?

Psychorider
May 15, 2009
If you mean literally creating variables named al1, al2, etc, then nothing will do that other than declaring them yourself. If you need a variable number of ArrayList, you can use an array of ArrayList or an ArrayList of ArrayList. What do you need it for exactly?

epswing
Nov 4, 2003

Soiled Meat
The way you're thinking about it, you'd create them but wouldn't be able to use them (you wouldn't magically be able to utilize al1, al2, etc). You have to put them somewhere. If the number of lists you want to create is variable, use an ArrayList instead of an array (like Psychorider suggests):

code:
List<ArrayList<String>> listOfLists = new ArrayList<ArrayList<String>>();

for (int i = 0; i < num; i++) {
    listOfLists.add(new ArrayList<String>());
}

listOfLists.get(0).add("Hello"); // add "Hello" to the first ArrayList.

Coredump
Dec 1, 2002

I thought I was using Arraylist. The idea is I want to make a loop where I feed in a number and it spits out the number of arraylist for me. The program I'm working on is supposed to let someone enter in a bunch of names and specify a number of groups. Then the program is supposed to randomly take the names from the big list and stick them evenly into the number of list the user specifies. The idea is this program will be used in a situation where a teacher needs to split up everyone in class into even random groups.

So far my line of thinking was to stick all the names into an arraylist and use collections.shuffle to randomize the big list of arrays. Then I wanted to make a for loop to make the number of arraylist the user specifies. Then make some kind of loop that just goes through my big arraylist and copies, or moves the names into the newly created list.

Adbot
ADBOT LOVES YOU

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Coredump posted:

I thought I was using Arraylist. The idea is I want to make a loop where I feed in a number and it spits out the number of arraylist for me. The program I'm working on is supposed to let someone enter in a bunch of names and specify a number of groups. Then the program is supposed to randomly take the names from the big list and stick them evenly into the number of list the user specifies. The idea is this program will be used in a situation where a teacher needs to split up everyone in class into even random groups.

So far my line of thinking was to stick all the names into an arraylist and use collections.shuffle to randomize the big list of arrays. Then I wanted to make a for loop to make the number of arraylist the user specifies. Then make some kind of loop that just goes through my big arraylist and copies, or moves the names into the newly created list.

Why do you need more than 1 ArrayList for this? Load all the names in a single ArrayList. Use Collections.shuffle to randomize the order. Then just loop through it and after x names, increase the group #.

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