1

I have two jFrames: Frame1 and Frame2.

Frame1 has a jComboBox and a jButton; Frame2 has just a jButton.

Frame1 can open Frame2.

I have this code on Frame 1:

public class Frame1 extends javax.swing.JFrame {

public void addTextToComboBox(){
this.jComboBox1.removeAllItems();
this.jComboBox1.addItem("Hello");
}

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
this.addTextToComboBox();
}              

}

It works fine: The "Hello" string is added to the jComboBox when i click the jButton.

Now I have this code on Frame2:

public class Frame2 extends javax.swing.JFrame {

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Frame1 frame1=new Frame1();
frame1.addTextToComboBox();
}

}

This way, the "Hello" string is not added to the jComboBox on Frame1 when i click on the jButton on Frame2.

Why? Could someone get me a solution please?

Thanks in advance.

Elkin
  • 880
  • 2
  • 12
  • 26
  • 1
    See [The Use of Multiple JFrames, Good/Bad Practice?](http://stackoverflow.com/q/9554636/418556) – Andrew Thompson Feb 11 '16 at 06:05
  • *"This way, the "Hello" string is not added to the jComboBox on Frame1 when i click on the jButton on Frame2. Why?"* Because `frame1` (created by the second frame) is a **2nd instance of `Frame1`.** It is the second instance that has the combo. altered, but that instance is never displayed. This is really (really) basic OO, and should have been sorted out in simple apps. (i.e. 'not a GUI'). *"Could someone get me a solution please?"* SO is not a help desk, in case you are mistaken. – Andrew Thompson Feb 11 '16 at 06:09

1 Answers1

1

Because you are trying to add string to another instance of jComboBox on Frame1 that is not showing now.

If you want to add string to jComboBox that is showing now, you need to pass the object of Frame1 to Frame2 then call addTextToComboBox();.

Example:

One of the way you can write your Frame2 class as

public class Frame2 extends javax.swing.JFrame {

    Frame1 frame1;
    public Frame2(Frame1 frame1) {
        this.frame1 = frame1;
    }

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        frame1 = new Frame1();
        frame1.addTextToComboBox();
    }

}

And using it

public static void main(String[] args) {
    Frame1 f1 = new Frame1();
    Frame2 f2 = new Frame2(f);
}

You can read Object-Oriented Programming Concepts for better understanding of OOP concept.

ashiquzzaman33
  • 5,781
  • 5
  • 31
  • 42