This topic is 4374 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

Hi. I am a C++ programmer who started to program Java recently. I am using Netbean and it really looks cool to me. I placed a textarea, a button and Jlist. Now I want to do something really simple. I want to add the text in text area to Jlist. I did this but does work: String a1; a1 = jTextField1.getText(); jList1.addElement(a1); for some reason compiler doesnt know addElement. Error is :
init:
deps-jar:
Compiling 1 source file to /home/raha/JavaApplication1/build/classes
/home/raha/JavaApplication1/src/javaapplication1/NewJFrame.java:202: cannot find symbol
location: class javax.swing.JList
1 error
BUILD FAILED (total time: 0 seconds)


by the way I am using linux :) any idea why this is happening ? Thanks

Share on other sites
The function .add() is how java does things. For more info on what all the other java objects' member functions are, see here:

http://java.sun.com/j2se/1.5.0/docs/api/

Share on other sites
you should also install the Sun JDK instead of relying on gcj.
gcj is extremely old and incomplete.

JList btw doesn't have any method to add data at runtime directly.
You either initialise it with an array of Vector for a static list or a ListModel for dynamic data (in which case you will need to derive a ListModel type yourself or use one of the predefined ones like DefaultListModel in order to add and remove data at runtime).

The latter is the preferred way of working in non-trivial applications, as the ListModel can also be used to do custom rendering of output and helps separate the user interface from the data.

See the API documentation for full details on these classes.

Share on other sites
Thank you.
I want to add data in runtime.

Instead of Jlist what component would you recommend? Thanks

Share on other sites
DefaultListModel model = new DefaultListModel();JList myList = new JList(model);model.addElement( "Something 1" );model.addElement( "Something 2" );

Share on other sites
No no.
What I mean that how can I add a text for example from a text field while the program is running.

Is it possible to do this using Vector ? if yes how is it possible ?

Thanks

Share on other sites
Quote:
 Original post by bargastehWhat I mean that how can I add a text for example from a text field while the program is running.
You mean like when you hit a button or somethin'? Lookup what's called "action listeners" and you should be able to do what you want to do from there.

Share on other sites
I am using NetBean, NetBean generat the GUI code, so for example when I put a button then I can goto action property and then choose for example clickbutton (or mouse over, etc).
My problem is not handling the event. My problem is that this doesnt work:

but this works:

jTextPane1.setText(a1);

or even

jTextField2.setText(a1);

once I click the buttom the string a1 set itself in jTextPane1 or Jtextfield2 without any problem. but for some reason that I dont know NetBean Doesnt accept addElement or even add for Jlist.

Why ? :(

Share on other sites
Quote:
 Original post by bargastehMy problem is that this doesnt work: jList1.addElement(a1);

Yeah. Look at Son of Cain's post. addElement is a member function of DefaultListModel, not JList. So, you want to add your text to the model of the JList. The reason for this is because the items displayed in a JList depend upon the information in its model, so if you add info to the model, you're adding info to the JList. Just be sure to set the model accordingly as also shown in Son of Cain's post.
Quote:
 Original post by bargastehNetBean Doesnt accept addElement or even add for Jlist.

You can't use .add() with a JList. And as said, addElement() is not a member of JList at all. Did you look at that api reference I posted earlier? It tells you all the member functions of each of Java's objects.

Share on other sites

I tried this but didnt work:

private void jButton3MouseClicked(java.awt.event.MouseEvent evt) {    // TODO add your handling code here:                                    String a1;Vector list = new Vector ();a1 = jTextField1.getText();DefaultListModel jList1 = new DefaultListModel();JList myList = new JList(jList1);jList1.addElement( a1 );jTextField2.setText(a1);jTextPane1.setText(a1);    }

Share on other sites
You must call fireContentsChanged(...) from the DefaultListModel after you call addElement(...).

Share on other sites
Actually, I guess that call is not necessary:

import java.awt.BorderLayout;import java.awt.Dimension;import java.awt.event.KeyEvent;import java.awt.event.KeyListener;import javax.swing.DefaultListModel;import javax.swing.JFrame;import javax.swing.JList;import javax.swing.JTextField;public class ListTest {        public static void main(String args[]) {                DefaultListModel model = new DefaultListModel();        final JList list = new JList(model);                ((DefaultListModel) list.getModel()).addElement("Something 1");        ((DefaultListModel) list.getModel()).addElement("Something 2");        ((DefaultListModel) list.getModel()).addElement("Something 3");        ((DefaultListModel) list.getModel()).addElement("Something 4");                JFrame frame = new JFrame();        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        frame.getContentPane().add(list, BorderLayout.CENTER);                final JTextField field = new JTextField();        field.addKeyListener( new KeyListener() {            public void keyPressed(KeyEvent e) {                switch (e.getKeyCode()) {                    case KeyEvent.VK_ENTER:                        ((DefaultListModel) list.getModel()).addElement(field.getText());                        break;                }            }            public void keyTyped(KeyEvent e) {}            public void keyReleased(KeyEvent e) {}        });                frame.getContentPane().add(field, BorderLayout.SOUTH);                frame.setSize(new Dimension(400, 300));        frame.setVisible(true);            }    }

Hope it helps you get ideas =D

Son Of Cain

Share on other sites
Thanks for help, but still I couldnt figure out.
NetBean has a special structure for its GUI class (Auto generating).

we have:

public class NewJFrame extends javax.swing.JFrame {        /** Creates new form NewJFrame */    public NewJFrame() {        initComponents();    }private void initComponents() {jList1 = new javax.swing.JList();jScrollPane2.setViewportView(jList1);}

and

public static void main(String args[]) {        java.awt.EventQueue.invokeLater(new Runnable() {            public void run() {                new NewJFrame().setVisible(true);            }        });    }        // Variables declaration - do not modify                         private javax.swing.JButton jButton1;    private javax.swing.JButton jButton2;    private javax.swing.JButton jButton3;    private javax.swing.JLabel jLabel1;    private javax.swing.JList jList1;    private javax.swing.JPanel jPanel1;    private javax.swing.JPanel jPanel2;    private javax.swing.JScrollPane jScrollPane1;    private javax.swing.JScrollPane jScrollPane2;    private javax.swing.JScrollPane jScrollPane3;    private javax.swing.JTable jTable1;    private javax.swing.JTextField jTextField1;    private javax.swing.JTextField jTextField2;    private javax.swing.JTextPane jTextPane1;    // End of variables declaration                       }

and this is my click event:

    private void jButton3MouseClicked(java.awt.event.MouseEvent evt) {                                      String a1;Vector list = new Vector ();a1 = jTextField1.getText();        //DefaultListModel model = new DefaultListModel();        //final JList jList1 = new JList(model);        //((DefaultListModel) jList1.getModel()).addElement("Something 1");        //((DefaultListModel) jList1.getModel()).addElement("Something 2");        //((DefaultListModel) jList1.getModel()).addElement(a1);     //jList1.add( "Something 1" );//jList1.addElement(list(0));jTextField2.setText(a1);jTextPane1.setText(a1);     // TODO add your handling code here:    }

but I have a feeling that I dont need to do :

//DefaultListModel model = new DefaultListModel();
//final JList jList1 = new JList(model);

because I already have it before? :(

I am confused. NetBean is free. if you try you will see the generated code and what I exactly mean.

Any Ideas ?

Share on other sites
I know what you mean, I use netbeans too.

Netbeans instantiates your list, but it does not sets a model for it. You can use the same list instance to call setModel() passing an instance of DefaultListModel (or your custom list model) for it. That will work, guaranteed :D

Get away from generated code until you get the grasp of how the API works; Also, always stick to the API, never to generated code - it helps you be productive, but you should understand what is actually happening if you want to use such a benefit properly ;)

Son Of Cain

[Edit: fixed typos]

Share on other sites
Do you have any idea that how I can do it in Netbean ? I did Java during my degree but I always loved C++ I only need to read some tutorials to refresh my memory.

Share on other sites
Ok, I did this and it works but there is a problem:

DefaultListModel model = new DefaultListModel();
final JList jList1 = new JList(model);
jScrollPane2.setViewportView(jList1);

When I type something new in my jtextfield and press the button the Jlist change too, I mean the old value disapear and the new one show up in Jlist. What would be the solution ?

Share on other sites
What's so hard about writing code?
If there's no wizard, write it yourself...

In fact, don't use wizards and other helpers until you know how to do it yourself. In other words, ditch netbeans for a simple text editor (with maybe syntax highlighting).

Share on other sites
bargasteh, from what I can guess from your post, you are creating a new list model and list box each time in your action listener. You should create and set and DefaultListModel once for the list box after creating it. In the action listener, you should then add the element to the previously created list model. Either by having stored it in a variable or through the appropriate accessor of JList.

I would also suggest you have a long look through the very well made Java API documentation and especially Swing tutorials/code samples like here.

While I personally don't advocate working completely IDE-less, I do agree with not relying on GUI builders like the one in Netbeans (I suggest Eclipse, but that's my opinion).

Share on other sites
Dude, your problem is not with the IDE, but with basic programming skills. When netbeans creates the JList instance for you, you have a REFERENCE to it (the variable!); use this reference to access the JList methods, including setModel() to add a ListModel implementor class to your list.

Refresh your Java knowledge before abusing IDE features... Trust me, that will save you a lot of pain =D

As the say goes, "you're trying to kill a fly using a Bazooka".

Son Of Cain

Share on other sites
nothing (fundamentally) wrong with IDEs, but you should never rely on them because you're not capable of doing something yourself.

That's hard (maybe even impossible) with some languages that store parts of the IDE generated code in binary (non-human readable) form, but Java isn't one of them.

So LEARN to do something by hand, then use the IDE to reduce your workload.
That way you can work where there is no IDE (or there is another one than the one you're used to).

Share on other sites
Ok Ok , I think there is a miss undestanding.
I never abused IDE, I actually love NetBean.
I was just playing with this IDE. At the time when I was in University we had to write everything up ourself, there was no IDE or fancy GUI creator.
Any way thanks for your help. I think Java is well behind C++ world. I probably will stick with the king of languages C++

Thanks

Share on other sites
It looks rather like Java is too far ahead of you to comprehend it, especially the architecture of the Swing library...

Share on other sites
I didn't say you were abusing the IDE... I was trying to say "don't use any IDE features until you fully comprehend what they are doing for you".

And your "problem" is quite a simple matter, I even posted some code to ilustrate that. I agree with jwenting, it seems that Java is far ahead of you - try getting a book on the basics before even dealing with swing, or else you'll have lots of trouble with it :D

Son Of Cain

Share on other sites
I only need to know a simple answer.
How would you add a model to jlist in NetBean.

That is all. I already started reading a Java Book and I am getting a grasp of it but the problem I have right now is that why such a simple thing was design to make you confuse in the first place by SUN ?

I would appreciate if you explain how it would be possible to add model to Jlist.

BitMaster was a lot more useful in this regard. instead of telling what I should do you could just explain this a little bit more so someone else also get encouraged to use Java.

BitMaster you are correct I do that in my click action listener all the time so it over write it every single time I click on button. I need to declare it some where outside. I tried that but because of the way Netbean is structured I became confused.

I am sure you all use NetBean or have it installed. it would be great if you add a textfield, button and Jlist and then try what I just said. I appreciate this.

Thank you

Share on other sites
Hey friend.. I already did that! But if you insist, I'll use your variable name:
jlist1.setModel(new DefaultListModel());

When netbeans generates code for an event, it creates a method that is called whenever that event is fired. In your case, it must be something like "jbutton1ActionPerformed(ActionEvent evt)". This is where you add the following:

((DefaultListModel) jlist1.getModel()).addElement( jtextfield1.getText() );

See? Me and jwenting were trying to save you future trouble; don't rely on this! Rather, follow up the API documentation, and you'll learn how to get the best out of netbeans.

BTW, Netbeans is also my IDE of choice. I code on it since version 3.5 - so I do have a bit of know-how to tell you that your problem is not tied to the IDE, but to your understanding of the API, instead. :D

Good luck now!

Son Of Cain