Reputation: 24705
With Netbeans, I have created a GUI form and added a JList
component. In order to add items, I have create a ListModel
according to many websites.
DefaultListModel<String> model = new DefaultListModel<>();
JList<String> list = new JList<>( model );
Problem is that the second line is automatically generated by Netbeans and it is not editable! So, I see
private javax.swing.JList<String> list;
...
list = new javax.swing.JList<>();
So how can I change that line to JList<>( model )
? I have to 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 that can be used. I see some questions similar to mine, but it is not clear for me what is exactly the problem and why I can not add/remove items in a normal way as expected!
Upvotes: 5
Views: 1885
Reputation: 22437
That because when netbeans generating code for you it will add access modifier private
for variables and for methods. You can change those to public
, so then you can change. To do that,
One method:
Right click on the jList in the navigator or in GUI. Next, go to customize code then, you will get pop up window in it chnage default code to custom property.
Or:
Go to jList property -> click on the code tab and in it change variable modifier private
to public
and then you can change code that you shown in the question.
UPDATE:
model = new DefaultListModel<>();
list = new javax.swing.JList();
list.setModel(model);
delete the argument inside the setModel()
and pass your model into it.
To add element:
model.addElement("anything here");
One last thing update your DefaultListModel
declaration to the above of your JForm constructor:
DefaultListModel<String> model;
public NewJFrame() {
initComponents();
}
Upvotes: 1