noobAlert
noobAlert

Reputation: 27

A basic logic issue whilst using setters and getters with Swing

Im writing a basic program to simulate a conversation between a user and the computer. I am trying to use a setter and getter to change the text in a textField in another class. The button is clicked and nothing appears in the textField. here is my code:

public class DialogueWindow extends JFrame {

    SuperDialogue SD = new SuperDialogue();
    JTextField textField = new JTextField();
    JButton Answer1 = new JButton();

    public DialogueWindow() {
        initUI();   
    }

    public void initUI() {

        JPanel panel = new JPanel();
        getContentPane().add(panel);
        panel.setLayout(null);

        JButton Answer1 = new JButton();
        Answer1.setBounds(102, 149, 113, 30);

        Answer1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {

                textField.setText(SD.getReply1());  
            }
        });

        panel.add(Answer1);

        textField = new JTextField();
        textField.setBounds(56, 74, 174, 45);
        panel.add(textField);

        setTitle("Dialogue");
        setSize(800, 600);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);    
    }
}

public class SuperDialogue {

    private String answer;

    public String getReply1(){
        return this.answer;         
    }

    public void setReply1(String a1){

    this.answer = a1;       
    }   
}
public class Conversation1 extends SuperDialogue {

public void Convo(){
    String firstLine = "hello";
    setReply1(firstLine);
    DialogueWindow DW = new DialogueWindow();
    DW.setVisible(true);
    DW.setSize(300,300);
    }   
}

public class Main {

public static void main(String[] args) {

    Conversation1 c1 = new Conversation1();
    c1.Convo();
    }
}

Upvotes: 0

Views: 62

Answers (1)

Kelvin
Kelvin

Reputation: 594

The SuperDialogue in your JFrame class is not the same as the one created in your main.

SuperDialogue SD = new SuperDialogue();

This line is creating a separate SuperDialog which does not has the same values. This one is never set, so getReply1() returns nothing.

Upvotes: 2

Related Questions