Initialize variable with constructor

后端 未结 2 760
你的背包
你的背包 2020-12-06 20:41

I have two class, first is my main class, and second class in my edit frame class.

public class RecordTableGUI extends JFrame implements ActionListener {
            


        
2条回答
  •  隐瞒了意图╮
    2020-12-06 21:08

    Java objects are somewhatlike real objects. And new does what its name suggests: it creates a new object. Let's take a simple example:

    Box box1 = new Box();
    Box box2 = new Box();
    box1.fillWithCandies(candies);
    

    box1 is a box filled with candies. box2 is a different box, which doesn't contain anything, because only box1 has been filled with candies.

    In your code, updateGUI's actionPerformed() method creates a new RecordTableGUI object, with the new name. That won't change anything to the first one.

    If you want updateGUI to modify the existing RecordTableGUI object, it needs to have a reference to this object:

    public class updateGUI extends JFrame implements ActionListener {
    
        private RecordTableGUI recordTableGUIToUpdateWhenOKIsClicked;
    
        public updateGUI(RecordTableGUI recordTableGUIToUpdateWhenOKIsClicked, ...) {
            this.recordTableGUIToUpdateWhenOKIsClicked = 
                recordTableGUIToUpdateWhenOKIsClicked;
            ...
        }
    
        public void actionPerformed(ActionEvent e) {
            if (e.getSource() == okButton) {
                newName = tf.getText();
                this.recordTableGUIToUpdateWhenOKIsClicked.setNewName(newName);
            }
        }
    }
    

    You should practice with simpler examples before using Swing. You should also respect the Java naming conventions. And the updateGui class should be a JDialog, not a JFrame.

提交回复
热议问题