我正在编写一个基本程序来模拟用户和计算机之间的对话。我正在尝试使用 setter 和 getter 来更改另一个类中 textField 中的文本。单击按钮后,文本字段中什么也没有出现。这是我的代码:
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();
}
}
最佳答案
JFrame 类中的 SuperDialogue 与 main.c 中创建的 SuperDialogue 不同。
SuperDialogue SD = new SuperDialogue();
这一行正在创建一个单独的SuperDialog
,它不具有相同的值。该值从未设置过,因此 getReply1() 什么也不返回。
关于java - 在 Swing 中使用 setter 和 getter 时的基本逻辑问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39342073/