简体   繁体   中英

JDialog and JFrame and new instance

I have 2 classes - a JFrame with a button, and a JDialog (a pop up) with few textfields on it. Now, when I click the button in JFrame a JDialog shows up:

/*** someClass class ****/  
JButton btnNewButton = new JButton("");
btnNewButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            jd = new jDialog();
            jd.setModal(true);
            jd.setVisible(true);    
        }
    });
public void doStuff(String one....String five){
   ... ..
  }

Now a jDialog pops up and i need to fill up some textfields inside it and click another button to confirm.

/*** jDialog class ***/   
JButton btnConfirm = new JButton("");
btnNewButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            one = 1_tf.getText();
            two = 2_tf.getText();
            three = 3_tf.getText();
            four = 4_tf.getText();
            five = 5_tf.getText();

            doAnything(one,two,three,four,five);

            1_tf.setText("");
            2_tf.setText("");
            3_tf.setText("");
            4_tf.setText("");
            5_tf.setText("");                           
        }
    });

public void doAnything(String one,String two,String three,String four,String five){

 someClass sc = new someClass();
 sc.doStuff(one,two,three,four,five);        
}

The textfield's values will be passed to doAnything() method, inside doAnything() is an instance of someClass class to access sc.doStuff() method and pass the values.

The problem now is that, Whenever I click confirm on jDialog class a new JFrame appears so there are 2 JFrames which is not what I want.. It's like whenever I do something on jdialog it creates a new JFrame instead of over lapping the original JFrame.

In the doAnything() don't recreate the someClass (it's better to read java naming convention -classes should start from capital letter) instances.

Define class field for the someClass instance? create it just once (if it's null) and reuse it.

That's probably because in the someClass constructor you create an show a JFrame. To avoid this problem, make a static reference to the doStuff() method.

Declare it as:

public static doStuff(one, two, three, four, five) {
    ...
}

and use it as:

someClass.doStuff(one, two, three, four, five);

Now, when you use the method, you don't have to create an object of someClass class, and then you don't have to call the constructor method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM