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
Sab669
Sep 24, 2009

http://pastebin.com/cuTQJ4nU

I've got an error on lines 96 & 97, it tells me I should change the type of myCar to InteriorColor / ExteriorColor respectively.

But what I don't understand is Interior/ExteriorColor extend CarDecorator, which extend Car. This is for my design patterns class, doing a bonus assignment where we need to mix and match random patterns we've learned this semester, trying to use Decorator + Singleton patterns. But yea, no idea where my logic is wrong. As far as I can tell I've followed my previous homeworks exactly.

Adbot
ADBOT LOVES YOU

Jabor
Jul 16, 2010

#1 Loser at SpaceChem

Sab669 posted:

But what I don't understand is Interior/ExteriorColor extend CarDecorator, which extend Car.

Sure, it extends Car. But it doesn't extend UniqueCar, which is what the type of your variable is.

baquerd
Jul 2, 2007

by FactsAreUseless

Sab669 posted:

http://pastebin.com/cuTQJ4nU

I've got an error on lines 96 & 97, it tells me I should change the type of myCar to InteriorColor / ExteriorColor respectively.

But what I don't understand is Interior/ExteriorColor extend CarDecorator, which extend Car. This is for my design patterns class, doing a bonus assignment where we need to mix and match random patterns we've learned this semester, trying to use Decorator + Singleton patterns. But yea, no idea where my logic is wrong. As far as I can tell I've followed my previous homeworks exactly.

What Jabor said. As an aside, UniqueCar is missing a synchronized keyword.

Sab669
Sep 24, 2009

I guess that's where I'm confused, because UniqueCar also extends Car, so isn't it technically a Car?

And in the two classes I've taken that use Java as the language, I've never heard of Synchronized.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem

Sab669 posted:

I guess that's where I'm confused, because UniqueCar also extends Car, so isn't it technically a Car?

Every UniqueCar is a Car, yes. That doesn't mean that every Car is a UniqueCar.

You'll notice that every class in Java extends from Object - does that mean that you can do something like the following?

code:
Integer whatever = new Integer(1);
whatever = new FileReader("hello.jpg");
Why not?

Why can you do this instead?
code:
Object whatever = new Integer(1);
whatever = new FileReader("hello.jpg");

baquerd
Jul 2, 2007

by FactsAreUseless

Sab669 posted:

I guess that's where I'm confused, because UniqueCar also extends Car, so isn't it technically a Car?

And in the two classes I've taken that use Java as the language, I've never heard of Synchronized.

UniqueCar is a Car
CarDecorator is a Car
InteriorColor is a Car

CarDecorator is not a UniqueCar
InteriorColor is not a UniqueCar

You are trying to set a UniqueCar = InteriorColor and that does not work.

For why to use "synchronized", here's a good article on Singletons. Reference the section "Multiple Instances Resulting from Incorrect Synchronization":
http://java.sun.com/developer/technicalArticles/Programming/singletons/

What exactly synchronized does and why you should use it appears to be out of the scope of your class however.

Malloc Voidstar
May 7, 2007

Fuck the cowboys. Unf. Fuck em hard.
The code Sab is working on is almost certainly for a low-level class and thus single-threaded.

ImplosiveF
Dec 17, 2008

by Fistgrrl
edit: Eh, nevermind, found an easier to use library. Problem solved.

ImplosiveF fucked around with this message at 00:06 on Dec 15, 2011

FateFree
Nov 14, 2003

I was wondering if anyone had a clever solution to this problem. I have a method that takes a String of html, and a Set<String> of ids pertaining to elements in the html. The purpose is to take the original html, find all of the tags that have one of the matched ids, and return a new string fragment of html.

So for example: Given this html and a set of ids {"1", "4"}

code:
<html>
 <div id="1"></div>
 <div id="2"></div>
 <div id="3"><span id="4"></span></div>
</html>
I would expect this result:

code:
<div id="1"></div>
<span id="4"></span>
Currently I am using JSoup which parses the html in memory, and then traverses it looking for elements matching the ids I supply, and that works fine. As a bit of a hobby though I'm looking for a way to do this very fast.

The only thing I can think of is a sax parser solution, where I maintain a map of String id > String htmlFragment. This seems pretty tough to implement correctly and efficiently. I wonder if a regular expression might work, although that seems pretty ugly. I'd welcome any ideas. And yes the html is valid xml.

FateFree fucked around with this message at 20:09 on Dec 15, 2011

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

FateFree posted:

I was wondering if anyone had a clever solution to this problem. I have a method that takes a String of html, and a Set<String> of ids pertaining to elements in the html. The purpose is to take the original html, find all of the tags that have one of the matched ids, and return a new string fragment of html.

So for example: Given this html and a set of ids {"1", "4"}

code:
<html>
 <div id="1"></div>
 <div id="2"></div>
 <div id="3"><span id="4"></span></div>
</html>
I would expect this result:

code:
<div id="1"></div>
<span id="4"></span>
Currently I am using JSoup which parses the html in memory, and then traverses it looking for elements matching the ids I supply, and that works fine. As a bit of a hobby though I'm looking for a way to do this very fast.

The only thing I can think of is a sax parser solution, where I maintain a map of String id > String htmlFragment. This seems pretty tough to implement correctly and efficiently. I wonder if a regular expression might work, although that seems pretty ugly. I'd welcome any ideas. And yes the html is valid xml.

Try Woodstox instead. This is what CXF uses and is therefore probably very good.

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
I've been reading the Newbie Interview thread and a while back someone suggested:

code:
 1   ...   10
             
 .
 .
 .

 91  ...  100 
As a suitable interview question, so I decided to go ahead and put it together. First pass had me write this:

code:
public static void grid(int a, int b){
	for (int i=0; i<a; i++){
		for (int j=0; j<b; j++){
				System.out.print(count);
				count++;
			}
			System.out.println();
		}
Which works well enough but has the 'ugly' problem of a condensed first line (assuming that a*b gets into double digits), and any number of condensed early lines when a*b has several digits.

So I wanted to rewrite my print function using the printf command and HOLY LORD I don't know how printf works. I could get around this using another value to keep track of the number of digits in count, and then a loop to print the appropriate number of spaces, but printf seems pretty powerful and useful so I'd like to learn how it works!

tl;dr

Given an int 'digits', how can I use printf to print the int 'count' inside a 'space' that's 'digits' long? ex:

code:
digits = 5; count = 143;

printf( MAGIC ) should produce  "  143".  That's two spaces and then 143.

I. M. Gei
Jun 26, 2005

CHIEFS

BITCH



Does anybody know if there's a way to take user inputs through a pop-up window in Java (on Windows 7, if that matters)? I've taken my share of college programming classes, and I seem to recall a concept like this showing up in at least one of my textbooks, but none of my classes have actually covered anything related to this (... yet).

I'm putting together a Java program that runs a certain series of calculations based on user inputs, and right now the "inputs" are just .txt documents that have to be typed up in Notepad before every individual run (after which the program scans in the .txt files line-by-line). If there's a way to save these input values after they've been typed into an input window (so the user doesn't need to re-enter old numbers a bajilliondy times), that'd be great too. :)


EDIT: Let me know if this question doesn't make sense to anyone. I might be able to explain it a bit better if I can find some of my old books.

I. M. Gei fucked around with this message at 16:06 on Dec 16, 2011

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
http://docs.oracle.com/javase/1.4.2/docs/api/javax/swing/JOptionPane.html

May be what you're looking for.

ex:

code:
Show a dialog asking the user to type in a String:
    String inputValue = JOptionPane.showInputDialog("Please input a value");

Or likewise

int inputValue = JOptionPane.showInputDialog("Please input a value");

if the user is to input an int.
edit: don't forget your import. import javax.swing.JOptionPane;

Newf fucked around with this message at 16:19 on Dec 16, 2011

Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."
Newf: Have you read the documentation for the Formatter? It contains some examples of doing similar things.

I. M. Gei
Jun 26, 2005

CHIEFS

BITCH



Thanks, I think I'll try those out a bit later today and see what happens.

Now if only I could find my old textbooks. :smith:

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.

Internet Janitor posted:

Newf: Have you read the documentation for the Formatter? It contains some examples of doing similar things.

Yeah, that's where I'm at. So

%[argument_index$][flags][width][.precision]conversion

is the format for a number in a 'formatted string'. So given that (most) of those arguments are optional, I'm not sure how to make an entry where it recognizes that the argument I'm inputting is for the width option?

I had tried something like:

printf("%digits", count);

which prints (if count=7 for example) "7igits".

I believe I see now that this is printing count as a decimal integer, and then going on to print "igits", but I guess I'm restuck now.

baquerd
Jul 2, 2007

by FactsAreUseless

Newf posted:

Yeah, that's where I'm at. So

%[argument_index$][flags][width][.precision]conversion

is the format for a number in a 'formatted string'. So given that (most) of those arguments are optional, I'm not sure how to make an entry where it recognizes that the argument I'm inputting is for the width option?

Well it's right there in the specification.

printf("%1$5d", count); //5 space padded number

Edit: forgot the required conversion value

baquerd fucked around with this message at 16:24 on Dec 16, 2011

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.

baquerd posted:

Well it's right there in the specification.

printf("%1$5d", count); //5 space padded number

Edit: forgot the required conversion value

OK, so part of my problem was that I hadn't payed enough attention to the format there to see that inputs aren't ambiguous. For example, flags are specified with a character set that's disjoint from the ints that specify ints, and an int without being followed by a $ will be interpreted as width instead of as an index.

The thing is that I can't put that 5 in there for width. The width was meant to correspond to a variable "digits", which is input-dependent.

I got it now though: printf("%"+digits+"d", count);

Thanks for the pointers.

Newf fucked around with this message at 16:38 on Dec 16, 2011

MrZig
Aug 13, 2005
I exist onl because of Parias'
LEGENDARY GENEROSITY.
What's with Java and null pointer exceptions, even though I check to see if the object is a null?

Ie check this code out:

code:
if (selected != null && mouseButton == 1 && (leftMouseClickPosition.x != mousePosition.x || leftMouseClickPosition.y != mousePosition.y))
{
	if (!selected.getDragging() && mousePosition.distance(Camera.getRelativex(selected.getDragArrowPoint().x),Camera.getRelativey(selected.getDragArrowPoint().y)) <30)
		{
			selected.setDragArrowMoving(true);
		}
{
It gives me a Null Pointer Exception on the second if line. Camera is a class being accessed in a static way, and the only object is selected yet I've specifically checked to see if it's null or not before using it. Any ideas?

Also, is there any way to go back to previous errors in Eclipse? Every time I run a new build it erases the old log.

Sedro
Dec 31, 2008
Try setting some of those values to temporary variables instead of using long conditionals. Then you can step through with a debugger and examine each value. It's also easier to read.

To answer: selected.getDragArrowPoint() probably returns null, and you are dereferencing it.

Also, if mousePosition.distance returns Integer, I think Java will automatically unbox it for the comparison and throw if the value is null. I'm sure someone will correct me though.

Here's hoping for non-nullable reference types.

Max Facetime
Apr 18, 2009

Sedro posted:

Here's hoping for non-nullable reference types.

Speaking of which, has anyone tried the Checker Framework and its Eclipse plugin?

Max Facetime fucked around with this message at 13:53 on Dec 17, 2011

Contra Duck
Nov 4, 2004

#1 DAD
e: hey new page

ComptimusPrime
Jan 23, 2006
Computer Transformer

MrZig posted:

What's with Java and null pointer exceptions, even though I check to see if the object is a null?

Ie check this code out:

code:
if (selected != null && mouseButton == 1 && (leftMouseClickPosition.x != mousePosition.x || leftMouseClickPosition.y != mousePosition.y))
{
 if (!selected.getDragging() && mousePosition.distance(Camera.getRelativex(selected.getDragArrowPoint().x),Camera.getRelativey(selected.getDragArrowPoint().y)) <30)
  {
   selected.setDragArrowMoving(true);
  }
{
It gives me a Null Pointer Exception on the second if line. Camera is a class being accessed in a static way, and the only object is selected yet I've specifically checked to see if it's null or not before using it. Any ideas?

Also, is there any way to go back to previous errors in Eclipse? Every time I run a new build it erases the old log.

How exactly are you initializing Camera? I don't want to make any assumptions, but you are saying you are trying to access Camera in a static way...

I am assuming when you call Camera.getRelativex(int x) you are doing some conversion between the camera position and the position that you pass it. When are you initializing the Camera? I am guessing that may be where your problem lies.

Sedro
Dec 31, 2008

I am in posted:

Speaking of which, has anyone tried the Checker Framework and its Eclipse plugin?
Tools like this help, but they're a band-aid over the problem. I haven't used this particular one, but I use something similar in .NET which saves me from writing plenty of boilerplate (which shouldn't be necessary in the first place). This seems much more robust though, so I'll definitely check it out for my next Java project.

My biggest concern would be IDE integration. Horrible plugins for otherwise great tools tend to be a deal-breaker for me.

MrZig
Aug 13, 2005
I exist onl because of Parias'
LEGENDARY GENEROSITY.
The Camera is initialized before that code is run, and all the variables needed are already initialized. The weird thing is, I've run the program hundreds of times and this error only happened once, and hasn't occurred again. Being a fluke doesn't stop me from worrying about it. I can't re-create it either.

The dragArrowPoint is initialized at the beginning of the Planet object's code, so it should always return something.

I've now made selected equal a separate object when it's supposed to be null (called nullPlanet - just an Planet object without meaning) so that I will no longer get any nullPointer exceptions from that.

Gough Suppressant
Nov 14, 2008
simple question with the JDBC hooking into MySQL.

Is there a way I can insert an entry, and at the same time return the automatically generated key that entry is now using?

I am aware that I can insert an entry, stating the automatic key should be returnable, and then get the key for the final entry in the database, but if multiple processes are accessing the database, this could return an incorrect result due to a second entry being added in before the key is returned.

pigdog
Apr 23, 2004

by Smythe

MonsterUnderYourBed posted:

simple question with the JDBC hooking into MySQL.

Is there a way I can insert an entry, and at the same time return the automatically generated key that entry is now using?

I am aware that I can insert an entry, stating the automatic key should be returnable, and then get the key for the final entry in the database, but if multiple processes are accessing the database, this could return an incorrect result due to a second entry being added in before the key is returned.
Check this out: http://dev.mysql.com/tech-resources/articles/autoincrement-with-connectorj.html

Gough Suppressant
Nov 14, 2008
Ahhh, that makes alot more sense now, thanks a bunch!

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
I'm gonna apologize in advance because I expect to be making GBS threads this thread up a lot over the next few days. I'm trying to use my Christmas break to get as much programming in as possible, and my biggest current goals are to build on my understanding of how OO programming and Java in particular work, and also to get a better understanding of some basic data structures and associated algos by writing them myself.

I figure I can do these things in combination. My plan is to start from this Node class:
code:
public class Node<E>{
	protected E value;

	public Node(){
		value = null;
	}

	public Node(E e){
		value = e;
	}

	public E getValue(){
		return value;
	}

	public void setValue(E e){
		value = e;
	}
}
And extend it into Node classes suitable for implementations in Singly, Doubly, and circularly linked lists, and then into trees and more general graphs. Finally, my end-goal for this endeavour is to extend my Graph class into a Finite State Automata class for reading RegExpressions, and also maybe write some code to output a graphical representation of a graph (or even FSA if I'm still rolling confidently at that point).

By the time I go back to class in January, I'd like to make my own 'package' that I can use in the future for my own academic type things, which includes all of my homemade classes.

I guess my only question for the moment is whether what I'm doing is totally misguided, or if I'm going about it in a fundamentally stupid way. Thoughts?

poemdexter
Feb 18, 2005

Hooray Indie Games!

College Slice

MonsterUnderYourBed posted:

simple question with the JDBC hooking into MySQL.

Is there a way I can insert an entry, and at the same time return the automatically generated key that entry is now using?

I am aware that I can insert an entry, stating the automatic key should be returnable, and then get the key for the final entry in the database, but if multiple processes are accessing the database, this could return an incorrect result due to a second entry being added in before the key is returned.

Shouldn't this be handled in the DDL for the table? Some column is the auto incrementing key?

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

Newf posted:

...
Most answers you get will be opinion, and here's mine: It's good to learn the basics the way you proposed learning them. I learn best the same way, write my own data structures and see how they interact with data, then growing them to handle other data and making real nontrivial programs with them.

The important part: after you write your own and fiddle with them, go back and use the ones provided by the JDK or Apache's or Google's open source libraries. It's more pragmatic to use the classes that professional programmers use instead of just your own.

baquerd
Jul 2, 2007

by FactsAreUseless

Newf posted:

And extend it into Node classes suitable for implementations in Singly, Doubly, and circularly linked lists, and then into trees and more general graphs. Finally, my end-goal for this endeavour is to extend my Graph class into a Finite State Automata class for reading RegExpressions, and also maybe write some code to output a graphical representation of a graph (or even FSA if I'm still rolling confidently at that point).

By the time I go back to class in January, I'd like to make my own 'package' that I can use in the future for my own academic type things, which includes all of my homemade classes.

I guess my only question for the moment is whether what I'm doing is totally misguided, or if I'm going about it in a fundamentally stupid way. Thoughts?

It's cool to learn the guts of a basic implementation for these classes and you'll learn a lot on the way. But rather than using them for future academic projects, you'd be better served to learn how to use and, if needed, extend the standard library classes (or third party libraries) which will generally serve you better than rolling your own solutions in terms of basic data structures.

In particular, writing a regular expression parser can be fun, but almost certainly will not result in something you want to use over the built in regular expressions.

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
Yeah, to clarify, I understand and expect that pretty well all of this will exist entirely as an exercise, but I mean to say that I'd like to continue on updating and refining my own library of code as I learn new things.


I'm in trouble already though, and it's with a dumb thing that's going to betray my total lack of understanding:

code:

SLinkNode.java:


public class SLinkNode<E> extends Node{
	protected SLinkNode<E> next;

	public SLinkNode(E e){
>>>		super(e);
		next = null;
	}

	public void setNext(SLinkNode<E> n){
		next = n;
	}

	public SLinkNode getNext(){
		return next;
	}
}
I'm getting "uses unchecked or unsafe operations." on the arrowed line. The superclass is included in my previous post. Instead of super(e) I also tried

super.Node(e); --> cannot find symbol method Node(E)

and some other stupider things. Is there some special way to use a constructor with generics? Or some particularly good reading on how to work generics?


Should I, before getting into any of this, make myself understand Interfaces and use them throughout my adventures?

Malloc Voidstar
May 7, 2007

Fuck the cowboys. Unf. Fuck em hard.
public class SLinkNode<E> extends Node<E>, I think

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.

Aleksei Vasiliev posted:

public class SLinkNode<E> extends Node<E>, I think

Correcto. Thanks.

Luminous
May 19, 2004

Girls
Games
Gains

MonsterUnderYourBed posted:

simple question with the JDBC hooking into MySQL.

Is there a way I can insert an entry, and at the same time return the automatically generated key that entry is now using?

I am aware that I can insert an entry, stating the automatic key should be returnable, and then get the key for the final entry in the database, but if multiple processes are accessing the database, this could return an incorrect result due to a second entry being added in before the key is returned.

Also a note, but I believe getting the last inserted keys is safe from other concurrent access so long as it is in the same transaction.

I. M. Gei
Jun 26, 2005

CHIEFS

BITCH




I did a little playing around with this and yeah, I think this is what I need. Thanks.


Now I need help figuring out how to SAVE data entered into a JOptionPane. The only way I've come up with for doing this is to take the values entered in each field on the JOptionPane (stuff like Name, Sex, Date of Birth, etc.), copy each of these values into a new .txt document separated by blank spaces (using a name entered into one of said fields as a default filename, which the user can change in a popup window if desired), and then save this .txt file into a certain predesignated folder on the user's system. Then, if the user wants to open one of the saved files, the corresponding .txt file is opened from the aforementioned folder, and all of the values are scanned into their respective fields in the JOptionPane, in the same order they were written into the .txt file when they were saved.

My first question is whether there is an easier way to do this than the way I've just described. If so, then I'd like to know what it is and how to do it. If not, then here are my questions regarding the method I described above:

1.) How do I create a new .txt file in Java?
2.) How do I write values into a newly-created .txt file in Java? (Apparently I forgot how to do this awhile back and need some help jogging my memory :shobon:)
3.) How do I set up an option enabling a user to save a .txt file into a destination folder, and how do I enable the user to edit the "Save As" name that the file is saved under?
4.) How do I get my program to recognize the contents of one of the JOptionPane fields as a default "Save As" name for Question #3 above?
5.) If the user decides to open a previously saved file, how do I get the program to open the destination folder so the user can Browse it for the file they want?

Not sure if these questions make sense, but any help would be greatly appreciated. I've never dealt with JOptionPane stuff before, so this whole subject is new territory for me.

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
Understand that I am a Java/programming child, and my answers to these and any questions are almost certainly not the best answers available. That said, I think they can 'work'.

Dr. Gitmo Moneyson posted:

1.) How do I create a new .txt file in Java?
2.) How do I write values into a newly-created .txt file in Java? (Apparently I forgot how to do this awhile back and need some help jogging my memory :shobon:)
3.) How do I set up an option enabling a user to save a .txt file into a destination folder, and how do I enable the user to edit the "Save As" name that the file is saved under?
4.) How do I get my program to recognize the contents of one of the JOptionPane fields as a default "Save As" name for Question #3 above?
5.) If the user decides to open a previously saved file, how do I get the program to open the destination folder so the user can Browse it for the file they want?

1), 2), and 4) can all be accomplished with the FileWriter and PrintWriter objects. To write, for example, to a file whose name is input by a user, you can do something like:
code:
import javax.swing.JOptionPane;
import java.io.*;

public class Box{
	public static void main(String[] args){
		try{
			PrintWriter out = new PrintWriter(new FileWriter(JOptionPane.showInputDialog("Please input a filename:")));

			out.println("wtf");
			out.print(JOptionPane.showInputDialog("heyo"));
			out.close();
		}
		catch (Exception x){}
	}
}
edit: The initialization of the PrintWriter is a little dense in that code, but read it carefully and it'll make sense if you look at the constructors for PrintWriter and FileWriter. The code below expands that one line out a bit to make it more readable:
code:
PrintWriter out = new PrintWriter(new FileWriter(JOptionPane.showInputDialog("Please input a filename:")));

is the same as:

String file = JOptionPane.showInputDialog("Please input a filename:");
FileWriter fw = new FileWriter(file);
PrintWriter out = new PrintWriter(fw);
Note that the printing to the file and such is all done in the same try block. As far as I can tell it has to be this way. I do not really understand why. Also note that you have to 'close' the printwriter, or else nothing will actually be written to the file.

I don't really have any immediate ideas about questions 3) and 5).

Newf fucked around with this message at 16:17 on Dec 21, 2011

cenzo
Dec 5, 2003

'roux mad?
Preface - I've never dealt with Swing really. But the logic of what you're trying to do I can try to help with.

Dr. Gitmo Moneyson posted:


1.) How do I create a new .txt file in Java?
2.) How do I write values into a newly-created .txt file in Java? (Apparently I forgot how to do this awhile back and need some help jogging my memory :shobon:)
3.) How do I set up an option enabling a user to save a .txt file into a destination folder, and how do I enable the user to edit the "Save As" name that the file is saved under?
4.) How do I get my program to recognize the contents of one of the JOptionPane fields as a default "Save As" name for Question #3 above?
5.) If the user decides to open a previously saved file, how do I get the program to open the destination folder so the user can Browse it for the file they want?



1&4) Creation of a .txt file is as easy as looking at the File class. Specify the path for the file and the correct extension and bam, your File exists. You can get as creative/restrictive as you want, but the Constructor for File that you want is File(String pathname) ... you could also force an extension with String concatenation. Here's a little example:

code:
        final static String DOCPATH = "/documents/";

	public static void main(String[] args) {
		try{
                        //create a basic file
			File file = new File("/documents/myFile.txt"));

                        //create a file with a pre-defined path and user specified file name
                        File userNamedFile = new File(DOCPATH + JOptionPane.showInputDialog("Please provide file name and extension"));
		}
		catch (Exception ex){
			//catch block
		}
2) For 2, Newf was onto something but you don't need a PrintWriter AND a FileWriter. Both have constructors that accept File objects (or a pathname as a String) -- so both of these would work (given the above code example):

code:
PrintWriter writer = new PrintWriter(userNamedFile);

PrintWriter writerByString = new PrintWriter(DOCPATH + JOptionPane.showInputDialog("Please provide file name and extension"))

3&5) For picking an Open... or a Save As... dialog I'd recommend looking at the JFileChooser class, specifically the showSaveDialog(Component parent) and the showOpenDialog(Component parent) methods, and their return values. The JFileChooser Constructor will also allow you to specify a starting point for the file system tree.


If you need help with the actual implementation of 3&5 now that you have the tools, just yell.

Adbot
ADBOT LOVES YOU

wins32767
Mar 16, 2007

Maven question: My project has a bunch of XML and XSL files. What's the canonical place to put those sorts of things so that the POM does the right thing when packaging them up for distribution?

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