tags:

views:

86

answers:

3

Hi , I am using netBeans editor to create desktop application . and i want to add Component without using drag and drop way. I am trying code like this for adding JList to JPanel but nothing showed

JList jl = new JList();
    Vector<String> v= new Vector<String>();
    v.add("one");
    v.add("Two");
    v.add("Three");
    jl.setListData(v);
    JScrollPane js = new JScrollPane(jl);
    js.setLocation(50, 50);
    js.setSize(100, 100);
    js.setVisible(true);
    jPanel1.add(js);
+1  A: 

The scroll list doesn't appear, or the data items in the list? Also, you're setting the position manually. Seriously, don't do that -- use a layout manager, many of which are available and you can easily use in the Netbeans GUI editor Mattise.

If the main window is under the control of a layout manager and then you add something to it that specifies its position and size, all mayhem will break loose. Namely, the layout manager will overwrite this, possibly with the result of size becoming 0, 0.

What you need to do is create a JPanel in your layout manager to hold the position of the new component and make sure it has a known field name you can reference and use to add to. Make sure that Panel also has FlowLayout or something in the properties.

Chris Dennett
+1 for advocating a layout manager!
trashgod
A: 

I want to add Component without using drag and drop way.

Here's a simple JList example that doesn't use the NetBeans' GUI editor. See How to Use Lists for more.

import java.awt.*;
import java.util.Random;
import javax.swing.*;

public class JListTest {

    private static final Random random = new Random();

    public static final void main(String args[]) throws Exception {
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                createAndShowGUI();
            }
        });
    }

    private static void createAndShowGUI() {
        final DefaultListModel dlm = new DefaultListModel();
        for (int i = 0; i < 1000; i++) {
            dlm.addElement("Z" + (random.nextInt(9000) + 1000));
        }
        final JList list = new JList(dlm);

        JFrame frame = new JFrame("Test");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.add(new JScrollPane(list), BorderLayout.CENTER);
        frame.pack();
        frame.setVisible(true);
    }
}
trashgod
A: 

you may want to call repaint() when you dynamically create GUI elements.

Jan Kuboschek