gpt4 book ai didi

java - 在单独的类中使用 ActionListener 使用原始类中 JTextfield 的数据

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:13:14 25 4
gpt4 key购买 nike

我正在努力学习 Swing 和 JFrame,因此我正在创建一个非常简单的程序,询问您的姓名,然后显示一个框,告诉您输入的内容。我正在尝试使用与第一个类不同的类来充当 ActionListener 并显示输入的名称。但是它对我不起作用。我尝试在第二个类中创建一个构造函数,该构造函数将一个实例变量设置为在 JTextfield 中采用的值,但它没有按我预期的那样显示。请看一下;

The prompt screen

I want it to say "You've Submitted the name Imray"

这是我的代码(我已经正确导入了所有库,但为了空间的缘故省略了)

这是主类...

public class NamePrompt extends JFrame{


private static final long serialVersionUID = 1L;

String name;

public NamePrompt(){

setLayout(new BorderLayout());

JLabel enterYourName = new JLabel("Enter Your Name Here:");
JTextField textBoxToEnterName = new JTextField(21);
JPanel panelTop = new JPanel();
panelTop.add(enterYourName);
panelTop.add(textBoxToEnterName);

JButton submit = new JButton("Submit");
submit.addActionListener(new SubmitButton(textBoxToEnterName.getText()));
JPanel panelBottom = new JPanel();
panelBottom.add(submit);

//Add panelTop to JFrame
add(panelTop, BorderLayout.NORTH);
add(panelBottom, BorderLayout.SOUTH);

//JFrame set-up
setTitle("Name Prompt Program");
//setSize(300, 150);
pack();
setLocationRelativeTo(null);


}



public static void main(String[] args) {
NamePrompt promptForName = new NamePrompt();
promptForName.setVisible(true);
}

这是 ActionListener 类:

public class SubmitButton implements ActionListener {

String nameInput;

public SubmitButton(String textfield){
nameInput = textfield;
}

@Override
public void actionPerformed(ActionEvent submitClicked) {
Component frame = new JFrame();
JOptionPane.showMessageDialog(frame , "You've Submitted the name " + nameInput );
}
}

最佳答案

您在创建时将一个空的 String 传递到 ActionListenerSubmitButton 中,一旦文本更改,它就永远不会更新JTextField textBoxToEnterName 所以什么都不会显示。

您可以传递 textBoxToEnterName JTextField 以在需要时访问该值:

class SubmitButtonListener implements ActionListener {

private JTextField textfield;

public SubmitButtonListener(JTextField textfield) {
this.textfield = textfield;
}

@Override
public void actionPerformed(ActionEvent submitClicked) {
Component frame = new JFrame();
JOptionPane.showMessageDialog(frame, "You've Submitted the name "
+ textfield.getText());
}
}

关于java - 在单独的类中使用 ActionListener 使用原始类中 JTextfield 的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13714119/

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