gpt4 book ai didi

java - 需要我的 GUI 从 JTextField 读取并在 JPanel 中显示

转载 作者:行者123 更新时间:2023-12-02 12:02:09 25 4
gpt4 key购买 nike

我已向文本字段添加了一个 Action 监听器。当按下 btnReadString(按钮读取字符串)时,程序应该读取文本字段上的内容并显示在 JPanel 上。但面板上没有任何显示。

stringTextField.addActionListener(new ActionListener() {
public void stringTextField (java.awt.event.ActionEvent e) {
if(e.getSource()==btnReadString) //when the button is pressed
{
String stringParameter = stringTextField.getText(); //gets the text and puts it on this string called "stringParameter"
textPane.setText(stringParameter);//the JPanel is set to what is on the string.
}

}

@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub

}
});

最佳答案

ActionListener 的功能应该放在 actionPerformed 方法中,因为没有调用 stringTextField 方法...

stringTextField.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==btnReadString) //when the button is pressed
{
String stringParameter = stringTextField.getText(); //gets the text and puts it on this string called "stringParameter"
textPane.setText(stringParameter);//the JPanel is set to what is on the string.
}
}
});

但是,根据代码,ActionListener 应该附加到 btnReadString 而不是字段,因为上述逻辑永远不会导致执行任何内容(如事件源永远不会是 btnReadString)

btnReadString.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String stringParameter = stringTextField.getText(); //gets the text and puts it on this string called "stringParameter"
textPane.setText(stringParameter);//the JPanel is set to what is on the string.
}
});

我建议仔细看看 How to Write an Action ListenerHow to Use Buttons, Check Boxes, and Radio Buttons了解更多详情

关于java - 需要我的 GUI 从 JTextField 读取并在 JPanel 中显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47169690/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com