Editing the auto-generated netbeans code

With Netbeans, I created a GUI form and added a component JList

. To add elements, I have created ListModel

according to many websites.

DefaultListModel<String> model = new DefaultListModel<>();
JList<String> list = new JList<>( model );

      

The problem is that the second line is automatically generated by Netbeans and is not editable! So I see

private javax.swing.JList<String> list;
...
list = new javax.swing.JList<>();

      

So how can I change this line to JList<>( model )

? I must say that in the generated code I see

 list.setModel(new javax.swing.AbstractListModel<String>() {
        String[] strings = { "String" };
        public int getSize() { return strings.length; }
        public String getElementAt(int i) { return strings[i]; }
    });

      

I don't know how this can be used. I see some questions similar to mine, but it's not clear to me what the problem is and why I can't add / remove items in the usual way as expected!

+3


source to share


1 answer


This is because when netbeans generates the code for you, it will add an accessor modifier private

for variables and methods. You can change them to public

, so you can change. For this

One method:

Right click in jList in navigatoror in a graphical interface. Then go to customize code then you will get popup in it chnage the default code into custom property .

Or:

Go to jList property -> click the code tab and in it change the modifier of the variable private

on public

, and then you can change the code you provided in the question.

UPDATE:



model = new DefaultListModel<>();
list = new javax.swing.JList();

list.setModel(model);

      

remove the argument inside setModel()

and pass your model to it.

To add an element:

model.addElement("anything here");

      

Last update of your declaration DefaultListModel

for your JForm constructor:

DefaultListModel<String> model;
public NewJFrame() {
    initComponents();
}

      

+1


source







All Articles