Dean_Grobler 48 Posting Whiz in Training

Hi there,

This is just going to be a quick question. Also just note that I am i some "remote location" so I cant even show you my code.
But what I want to know is this: Say you have a package called "myPackage" and inside that you have 2 classes, firstClass() & secondClass(). In firstClass() there is a List. At runtime I want to use the getSelectedIndex() method of the List from secondClass().

So if firstClass() & secondClass() have public access, you do this right?:

int index = myPackage.firstClass.myList.getSelectedIndex();

Hope I have the right idea here.. But in my app that I'm working on currently (I'm using Netbeans for this) I keep on getting errors stating that it cannot find "myPackage" or "firstClass" or whatever. What can be the problem? If both classes have public access how can an error like that appear?

Thanks for your help!
Sorry if the questions if a bit vague/confusing...

Dean_Grobler 48 Posting Whiz in Training

Or you can use an ArrayList and convert it to an array..

Dean_Grobler 48 Posting Whiz in Training

Hi there,

I'm getting an error saying: non-static variable MainList cannot be referenced from a static context.

My snippet of code where the error is occuring:

//this method is in a class called ViewContact
public void printInfo(){
	int index = MainScreen.MainList.getSelectedIndex();
}

Now the List "MainList" is in a class called MainScreen and has public access.
What I'm trying to do, is get an int from the getSelectedIndex() method of the
List class.. But the error above gets thrown.

Thanks for any help!

Dean_Grobler 48 Posting Whiz in Training

hehe cool thanks guys. So outside the while loop, and outside the try block. And no lol, that's not my real catch, I'll add something in there at a later stage :-) Otherwise that's a million guys!

Dean_Grobler 48 Posting Whiz in Training

Yes I did declare it as ArrayList<Contact>. Cool, otherwise it is also right where I am not converting it to an array INSIDE the while loop. OUTSIDE the while loop is the place to do it hey?

Dean_Grobler 48 Posting Whiz in Training

Hi there,

In my little code snipet below I am trying to convert an arraylist to an array of type contact. Obviously it's expecting an arraylist of type contact to convert it to an array of type contact. But it's picking up the arraylist as type object for some reason.

public void readInfo(){
try{
    inputStream = new BufferedReader(new FileReader("conList.txt"));
}
catch(FileNotFoundException e){}

try{
    while ((conInfo = inputStream.readLine()) != null) {
         infoArray = conInfo.split("\\s+");

         //Create new Contact Object
         Contact newCon = new Contact(infoArray[0],infoArray[1],infoArray[2],
                                        infoArray[3],infoArray[4],infoArray[5]);

         //Add new Contact to ArrayList
         contactObj.add(newCon);

        MainList.add(infoArray[0]+" "+infoArray[1]); 
    }

    //Convert ArrayList to Array
    Contact ia[];
    ia = contactObj.toArray();// Error: incompatible types, 
                              // required: Contactkeeper.contact
                              // found: java.lang.Object[]

   }
   catch(IOException v){}


}

In my code you can see the comment on where the error is thrown and what error is thrown. Thank you so much for your help!

Dean_Grobler 48 Posting Whiz in Training

Good mornin' mate,

If you have internet explorer, once you viewing a webpage, simply click on 'view > Source'. That will display the HTML of the webpage. Most often you'll get code like java,javascript etc will be in seperate files used in the webpage through simple "href" links (That then obviously stops you from seeing that).

Anyways, hope you find this usefull!

Dean_Grobler 48 Posting Whiz in Training

As long as it looks okay to you then I'm happy. Thanks again for everything!
Have a great day! or night.. wherever you are in the world..
Cheers

Dean_Grobler 48 Posting Whiz in Training

Ah ofcourse, didn't see that there.

What is the <contact> for in the ArrayList<contact>?
The API is a bit unclear about this.

Other than that, you think my code will run as expected?
I wish I could test it myself but unfor tunately I am unable to do so as I'm not at a PC with the JDK installed...

Dean_Grobler 48 Posting Whiz in Training
BuffereReader inputStream;
String conInfo;
try{
    inputStream = new BufferedReader(new FileReader("conList.txt"));
    //Creates new ArrayList
    ArrayList contactObj = new ArrayList();	

    while ((conInfo = inputStream.readLine()) != null) {
         String infoArray = conList.split("\\s+");

         //infoArray[0]="dean"
         //infoArray[1]="grobler"
         //infoArray[2]="0794400541"
         //infoArray[3]="NA"
         //infoArray[4]="NA"
         //infoArray[5]="dean3446@gmail.com"
	
	//New Contact object gets created
        contact newCon = new Contact(infoArray[0],infoArray[1],infoArray[2],
				     infoArray[3],infoArray[4],infoArray[5]);
 	
	//Contact object gets added to arraylist
	contactObj.add(newCon);

	}//Close while loop

}catch(IOException e){ //handle error }

Thank you for everybodies help. I feel rather confident that the above code
is closer. If it is, after the entire txt has been read line by line (as
an example given right at the top of this post with the 3lines)

The result will be an ArrayList that now stores 3 Contact objects?:
contactObj[0].getName = "Dean"
contactObj[1].getName = "Avril"
contactObj[2].getName = "Peter"

This must be right now?

Dean_Grobler 48 Posting Whiz in Training

Okay, so I've change the (" ") in the split method. also the arguments for the while() loop. I really hope I'm getting closer? This is for my final assignment and I'm struggling alot!

also now, in the while() loop. Where a new Contact gets created called con001. Wouldn't this then just create a new con001 contact over and over again? Isn't there some way to make the next contact object be called con002, then con003 etc?

BuffereReader inputStream;
String conInfo;
try{
    in=new BufferedReader(new FileReader("conList.txt"));
    while ((conInfo = inputStream.readLine()) != null) {
         String infoArray = conList.split(\s);

         //infoArray[0]="dean"
         //infoArray[1]="grobler"
         //infoArray[2]="0794400541"
         //infoArray[3]="NA"
         //infoArray[4]="NA"
         //infoArray[5]="dean3446@gmail.com"

         contact con001 = new Contact(infoArray[0],infoArray[1],infoArray[2],infoArray[3],infoArray[4],infoArray[5]);
 
}catch(IOException e){ //handle error }

This is impossible :-(

Dean_Grobler 48 Posting Whiz in Training

I did this quick? Am I on the right track?

BufferedReader in;
String conInfo;
try{
     in=new BufferedReader(new FileReader("conList.txt"));
     while(in.readLine() != 0){
           String[] infoArray = conInfo.split(" ");
           //infoArray[0] = "dean"
           //infoArray[1] = "grobler"
           //infoArray[2] = "0794400541"
           //infoArray[3] = "NA"
           //infoArray[4] = "NA"
           //infoArray[5] = "dean3446@gmail.com"

           Contact con001 = new Contact(infoArray[0],infoArray[1],infoArray[2],infoArray[3],infoArray[4],infoArray[5]);

}
catch(IOException e){ //handle exception }

I know this is suppose to be easy but I've been having a bad week lol, my brain can't wrap around this... :-(

Dean_Grobler 48 Posting Whiz in Training

Hi there,

A thread was started earlier about splitting up a String using the split() method of the string class. Reading that did help me quite a lot in solving a problem of mine that is VERY similiar.

Say I have this in a txt file:
"Dean Grobler 0794400541 NA NA dean3446@gmail.com
Avril Gibson 0825426532 NA NA avril@gmail.com
Peter Pumpkineater 0724128945 0119548714 peter@webmail.com"

and I have this class:

public class Contact
{
	String name,
	       surname,
	       mobile,
  	       home
                work
	       email;
		   
	public Contact(String name, String surname, String mobile, String home,
			String work, String email)
	{
		this.name = name;
		this.surname = surname;
		this.mobile = mobile;
 		this.home = home;
		this.work = work;
		this.email = email;
	}

	/*.
	  .
  	  .getters and setters etc.
	*/
}

How would I continue reading line by line in the file (regardless of how many lines of information there is in the .txt) and keep on popping out 'Contact objects'? So then in the above .txt example it would create 3 Contact objects?

Dean_Grobler 48 Posting Whiz in Training

With the number the user then adds, and after you've converted it to an int.
Use a switch statement to take appopriate action depending on the user input...

Dean_Grobler 48 Posting Whiz in Training

I've tried this -->

/* This is from the application piece */
JFrame myframe = new JFrame("My Frame");
myframe.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
Runtime.getRuntime().exit(0);
}
});

/* This is from the action event of the button */
JButton close = new JButton("Close");
close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
myframe.dispatchEvent(new WindowEvent(close,WINDOW_CLOSING);
}
});

Seriously, just to close a Frame? It's ridiculous..

Dean_Grobler 48 Posting Whiz in Training

Hello there,

In one of my projects I'm working on currently. I have a 'cancel' button in my GUI window that is suppose to close the JFrame the button resides in. I have done some research on the web about this. But it seems like one has to write a fair amount of code for this little trival task. Does anyone know of a simple/short way of doing this?

Any help would greatly be appreciated,
Thanks!

Dean_Grobler 48 Posting Whiz in Training

Yeah, wouldn't help him. Just thought I'd let him know that it's pretty hard. If not impossible. Heck I don't know how to do it.. With the applet you'll get the .class though won't you? how you going to turn that back into a .java to SEE the code?

....Arrrrgh, shivy me timbers.

Dean_Grobler 48 Posting Whiz in Training

Oooh, I don't think that's possible man. That's obviously what they trying to avoid. depending if the game is a applet or a Servlet or something it might be more possible for the one or the other..

If you using internet explorer, click view > source. Then if you cant see any java code in there (which you probably wont). Then, I don't think you'll be able to then..

What website is it, just out of interest sake?

Dean_Grobler 48 Posting Whiz in Training

What you can also do, use math.random() to generate some radom number, parse it to an int, then use those ints as the value for the x and y coordinates. Then the button will just pop up where ever the heck it feels like! It will be crazy like a cartoon or something!!

Dean_Grobler 48 Posting Whiz in Training

Hey man, whatsup!
Check out the little piece of code here:

int btnClicked = 0;

public btnActionPerformed(actionEvent e) {
    if(btnClicked==10){System.out.println("You win!");
    else{btnClicked++;}
}

Then with the button moving and all that, there's a layoutManager (not sure which one) that you can set the x and y coordinates of the button in the JFrame. So just do some research in that. And then in your code, change the x and y coordinates for the button in the actionlistener after the btnClicked++ part..

It really won't be that hard I think..
Hope this helped!

Dean_Grobler 48 Posting Whiz in Training

Ah you can, thanks humans!!!

Dean_Grobler 48 Posting Whiz in Training

Okay what's going to be the easier one here now? By the sound of it the JList. Can you add an actionListener to a JList item?

Dean_Grobler 48 Posting Whiz in Training

Helooo,

Attached is a pic of my main screen of my program. Basicly it's a phone book app similiar to one you'd have on your phone. The thing that I can't wrap my mind around, is that you see the nice big textArea there?
After you've added a contact now. What can I use that the user can just click on the name of the contact in the textArea and the appropriate window will display for the contact?

As far as I know, you cant add an actionListener on a piece of text in a textArea. So what do I do? I've also considered packing the textArea full of JButtons displaying the persons name. But that just sounds a bit dodgy...

Oh yes and the contact I'm talking about is just a instance of my Contact class. Asin:

public Contact(String name, String surname, String mobile); //etc etc

Any help please!!

Dean_Grobler 48 Posting Whiz in Training

Ahh! I see, well that's pretty awesome then. I will make start doing that then, having a main() in more than just one class clearly has it's advantages. Otherwise thanks alot for the help :-)

Dean_Grobler 48 Posting Whiz in Training

Since I'm not at a PC with the JDK available is this all I have to do to make my code run? Also, since I'm new to Netbeans. Both of these classes have a main method in it, is that normal? I thought that only one class in your package can have the main method that would set the ball running for the entire program?

Dean_Grobler 48 Posting Whiz in Training

Hi there,

Consider the following code, this is a little 'snipet' from one of my classes:

private void jMenu1ActionPerformed(java.awt.event.ActionEvent evt) {                                       
    NewContact n = new NewContact();
}

The method is expected to open a new Frame, where the class of the new Frame is
called "NewContact". I've recently migrated to Netbeans 6.9.1 So sorry for all the
lengthy comments. I've also used the GUI builder Netbeans offers so that might
make the code rather lengthy also.. Anyways, here's the code for the Frame that
I am trying to invoke/show/pop-up/whatever:

/**
 *
 * @author Dean
 */
public class NewContact extends javax.swing.JFrame {

    /** Creates new form NewContact */
    public NewContact() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jTextField2 = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jTextField3 = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jTextField4 = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jTextField5 = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        jTextField6 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("New Contact");

        jLabel1.setText("Name");

        jLabel2.setText("Surname");

        jLabel3.setText("Mobile");

        jLabel4.setText("Home");

        jLabel5.setText("Work");

        jLabel6.setText("Email");

        jButton1.setText("Save");

        jButton2.setText("Cancel");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 36, Short.MAX_VALUE)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 137, …
Dean_Grobler 48 Posting Whiz in Training

okay perfect, the inner class thing sounds like a good idea. Would look more tidy and organised also like you said. Anyways, thanks again!

Dean_Grobler 48 Posting Whiz in Training

Oh yes! Just another quick question. If I were to use the first way now. Should both classes implement actionListener or just the second class?

Dean_Grobler 48 Posting Whiz in Training

I see, I think I'll prefer the first way, in the second way I'm gna end up writing too many method, if I have a method designed only for the purpose of calling another method.
Anyways, thank you so much! This was quite helpfull :-)

Dean_Grobler 48 Posting Whiz in Training

Cool, okay so say I have one class that's just my UserInterface. Then in that interface I have a actionListener registerd on a button. Now normaly you do that and then you have a method actionEvent/actionPerformed method in the same class that then says what should happen when that button is clicked.

What I want to do, is have this actionEvent/actionPerformed method, in ANOTHER class. Make sense?

Dean_Grobler 48 Posting Whiz in Training

Hi there,

I just wanted to find out if one can have a actionListener() in one .class file and then have the actionEvent() in another .class file? If not, how would I go about to get the same effect?

Thanks!

Dean_Grobler 48 Posting Whiz in Training

I had a look at the GridBagLayout and it looks SUPER complicated! But if that's the only option I have then so be it. This JFormDesigner, obviously it generates the code for you after you made the design, I've heard that the code that these things through out is very unmanageable and messed up. Is this true?

*AddressBook is cool, although I was looking for something more 'techy' LOL. Something like 'PersonaPad' or something..

Dean_Grobler 48 Posting Whiz in Training

Hello!

Attached is a file (GUI.png), I quickly did this in excel so.. It looks pretty crappy obviously. But when you take a look at the image and the layout of the components etc. What would you say is the best LayoutManager to use with this? GUI design is fun, but I also hate it and I'm not that good with it..

*PS if you can think of a better name for the program (it's just a simple app that stores peoples details, like a phonebook on your cell) please let me know! "ContactKeeper" sounds too cheesy.. And it makes it sound cheap.

Thanks!

Dean_Grobler 48 Posting Whiz in Training

Geez.. so much trouble just for adding an image, I don't want to hack into NASAS satalites or anyting, just want a stupid image to display. Why could it just be more like HTML (<img src="theImage.png"/> and there you go? Ohwel.. Thanks for all the help, I'll try and crack this thing tonight then.

Dean_Grobler 48 Posting Whiz in Training

Thanks Katana24! As I said I don't have access to a PC with the JDK on now but I will deffinately try out your advice as soon as I can. :-)

Dean_Grobler 48 Posting Whiz in Training

I'm at work at the moment and here the PC that I'm working on can barely open notepad. Never mind install the JDK and run cmd prompt etc. So I'm going to have to wait till I get home to try this out..

But I'll go try the getCanonicalPath() thing and see what happens. I don't if this could be a factor: I'm using Eclipse on this thing. And what I thought I should do is just go to the folder on my PC that stores the .java and .class file (the workflow directory that Eclipse creates) and paste the image in there.

Don't know then if eclipse is messing this up then..

Dean_Grobler 48 Posting Whiz in Training

Thanks for the link on the GridBagLayout Tutorial! Will deffinately work through that just now.
So about the ImageIcon thing, if the filename is correct and the path is correct(its in the same directory as the .class file) and it still doesn't work then that means I'm pretty screwed? ...So frustrating.
Is the only option ImageIcon to put images in a GUI? Otherwise I'll try something else..

Dean_Grobler 48 Posting Whiz in Training

Ahh! *Epiphany* okay cool.. For some reason I thought that all components should be inside a panel before you add it to the container? Guess not..

I had a look at GridBagLayout, looks very complicating. I'll read up on it some more then and try it out.

Dean_Grobler 48 Posting Whiz in Training

Cool I'll try testing it then. If it comes back 'negative' what would the most likely causes be that it's not working? just Filenames that might be spelled wrong or something?

I used lots of panel (I know it looks like crap) becauase I struggled getting a proper LayoutManager that will display all the components right underneath each other centered.. If you know of a better LayoutManager other than GridLayout please let me know? It's not fun working with that many Panels..

Dean_Grobler 48 Posting Whiz in Training

Hi there,

In the code below my ImageIcon isn't showing when I run the program. I always struggle with adding Images in my GUIs and it's irritating. Is there some all important rule that I should know or something?

//Create window Components
	JLabel lblrequest = new JLabel("Enter amount of square meters:");
	JTextField inpt = new JTextField(10);
	JButton btnEnter = new JButton("Enter");
	JButton btnClear = new JButton("Clear");

	JLabel lblAdhesive = new JLabel("Adhesive:");
	JLabel AdhOutput = new JLabel("0 X 20kg bags.");
	JLabel lblGrout = new JLabel("Grout:");
	JLabel GrtOutput5 = new JLabel("0 X 5kg bags.");
	JLabel GrtOutput20 = new JLabel("0 X 20kg bags.");
	ImageIcon image = new ImageIcon("NationalTile.png");
	
	public Container createContentPane(){
		
		//Add window Components
		JPanel imagePanel = new JPanel();
		imagePanel.setLayout(new FlowLayout());
		JLabel imgLabel = new JLabel(image);
		imagePanel.add(imgLabel);
		
		JPanel topPanel = new JPanel();
		topPanel.setLayout(new FlowLayout());
		topPanel.add(lblrequest);

		JPanel textPanel = new JPanel();
		textPanel.add(inpt);
		
		JPanel btnPanel = new JPanel();
		btnPanel.add(btnEnter);
		btnEnter.addActionListener(this);
		btnPanel.add(btnClear);
		btnClear.addActionListener(this);
		
		JPanel AdhesivePanel1 = new JPanel();
		AdhesivePanel1.setLayout(new FlowLayout());
		AdhesivePanel1.add(lblAdhesive);
		
		JPanel AdhesivePanel2 = new JPanel();
		AdhesivePanel2.add(AdhOutput);
		
		JPanel GroutPanel1 = new JPanel();
		GroutPanel1.setLayout(new FlowLayout());
		GroutPanel1.add(lblGrout);
		
		JPanel GroutPanel2 = new JPanel();
		GroutPanel2.add(GrtOutput5);
		
		JPanel GroutPanel3 = new JPanel();
		GroutPanel3.add(GrtOutput20);
		
		//Add panels to Container
		Container c = getContentPane();
		c.setLayout(new GridLayout(10,1));
		c.add(imagePanel);
		c.add(topPanel);
		c.add(textPanel);
		c.add(btnPanel);
		c.add(AdhesivePanel1);
		c.add(AdhesivePanel2);
		c.add(GroutPanel1);
		c.add(GroutPanel2);
		c.add(GroutPanel3);
		
		return c;
	}

Thanks for taking a look at this!
*Just let me know if you want to see the rest of the code, sure it won't be needed though..

Dean_Grobler 48 Posting Whiz in Training

Hi there,

If I'm understanding you correctly. You can just use the 'getState()' method.
Like so:

yourCheckbox.getState();
//This will return a boolean value, i.e true or false

Hope this helped!

Dean_Grobler 48 Posting Whiz in Training

Okay so what you saying is that you basicly want to display another textField underneath another one? You can look up into all the Layout managers that Java offers.http://download.oracle.com/javase/tutorial/uiswing/layout/visual.html

What LayoutManager you currently using on your GUI?

Dean_Grobler 48 Posting Whiz in Training

Sorry I didn't mean it in a bad way, I'm not saying you hopeless. There's just confusion going on here that's funny. I'm no pro, I'm still a student, don't hardly have a year experience with java.

Dean_Grobler 48 Posting Whiz in Training

LOL, Actually had a good laugh reading this :-)

Dean_Grobler 48 Posting Whiz in Training

Are you too lazy or too incompetent to even start thinking about how you going to design this? So you just go onto some website, thinking "Hey, why don't I try my luck". With this attitute you not going to learn anything.
Go think about what classes you going to create, what the classes are going to do, how/what are the classes are going to communicate with each other, your GUI design etc...

Dean_Grobler 48 Posting Whiz in Training

Hello,

The name pretty much implies what it is, getter methods get variables, and setter methods set variables.

Say for instance you a have a class called Contact, the "getName()" method in the Contact class would return the Name variable.

Like so:

public class Contact
{
	String firstName,

	public Contact(String firstName)
	{
		this.firstName = firstName;
	}
	
	public String getfirstName()
	{
		return firstName;
	}
}

Setter methods then would set the Name variable, so you would invoke the "setName()" method of the Contact class like e.g Contact.setName("Xufyan"); And then the Name variable in the Contact class will be set to "Xufyan"..

So then this would be the code in your Contact class for the setter method:

public void setfirstName(String firstName)
	{
		this.firstName = firstName;
	}

Hope this helped!

Xufyan commented: nice +0
Dean_Grobler 48 Posting Whiz in Training

Heloooo...

If I get what you're saying, you mean that you can still drag the window and resize it when the program running and you don't want that?

Just go:

yourJFrame.setResizeable(false);
Dean_Grobler 48 Posting Whiz in Training

What might also work then in that case, is maybe just converting the string that you're getting to an int or what ever you want? As in:

myInt = Integer.parseInt(theStringThatYoureGetting);
Dean_Grobler 48 Posting Whiz in Training

Is line 2 part of a method? (it should be)

Aww crap, no it's not. It's under class level. Such a dumb mistake. I should remember that one can only declare/initialize under class level. Not work with the methods.(correct me if I'm wrong)

Otherwise thank you both for your help!

Dean_Grobler 48 Posting Whiz in Training

Hi there,

I've just switched to Eclipse. I've been using TextPad so Eclipse is pretty cool..
But I've been getting weird error messages that I don't understand/not used to.
Here they are:

JButton btnEnter = new JButton("Enter");
		btnEnter.addActionListener(this);

Here the Error says: Multiple markers at this line.
-Syntax on token "this", delete this token.
-Syntax error on token(s), misplaced construct(s).

What the hell?

And I also had to declare this (below) otherwise Eclipse got all cocky saying that I should.

static final long serialVersionUID;

What is this and why did I have to declare this?

Thanks for taking a look at this..