I would like to add elements to a list box on a jframe, from a different class however it doesn’t seem to work no matter what i try… i do not get an error or any feedback on whats wrong with this… but heres the layout i have, the listbox is using DefaultListModel lm2
I know how to add elements to a jList in the jframe class, but for some reason i am unable to add elments from another class even when adding this inside the jframe class:
public void log(String str) {
lm2.addElement(str);
}
and on my “other class”
frmMain doit = new frmMain();
doit.log("add to list box");
#
More details add- — >
#
I have 3 classes and here they all are:
frmMain.class
// jFrame class which builds the jframe (from jframe template)
public class frmMain extends javax.swing.JFrame {
/** Creates new form frmMain */
public frmMain() {
initComponents();
}
public void log(String str) {
lm2.addElement(str);
}
public DefaultListModel lm2 = new DefaultListModel();
}
RequestInfo.class
// RequestInfo.class, which is trying to add an item to the
// jlist but it doesn't add anything or error
public class RequestInfo {
public void ProcessReturnedInfo(String sData, boolean bWithLabel) {
frmMain fm = new frmMain();
fm.log("test test");
}
RS232Example.class
// My main class which sets the jFrame to visible
public class RS232Example {
public static void main(String[] args) throws Exception {
frmMain form = new frmMain();
form.setVisible(true);
}
}
I understand maybe i need to set form to visible on the RequestInfo.class, however i can’t do this, because it will continuously open the form multiple times, because this class method is called multiple times from an event…
if your listBox-model is set right (like
listBox.setModel(this.lm2);)I guess the following should work:
If you are wondering why this works and the code within RequestInfo does not, keep in mind, that you create a new frmMain with it’s own listModel for every call of
ProcessReturnedInfoIf you want to have only one Frame updated try to use the frame as singleton:
Change the constructor of
frmMainfrom public to private and add this to the class:Instead of calling
new frmMain()you must now usefrmMain.getInstance()inRequestInfoandRS232ExampleThat’s how you will always work on the same frame.
Good Luck.