[英]java swing, get value from ActionListener
I wanted to click on a button and have a pop up window where i can enter a string and that string will be outputted in the label, but i can't manage to return the string. 我想单击一个按钮,然后弹出一个窗口,我可以在其中输入一个字符串,该字符串将在标签中输出,但是我无法返回该字符串。
JButton btnName = new JButton("Name");
btnName.addActionListener(new ActionListener() {
String name;
public void actionPerformed(ActionEvent e) {
name = JOptionPane.showInputDialog("enter your name");
}
});
btnName.setBounds(10, 11, 89, 23);
frame.getContentPane().add(btnName);
JLabel lblPerson = new JLabel(name);
lblPerson.setFont(new Font("Tahoma", Font.PLAIN, 36));
lblPerson.setBounds(10, 188, 414, 63);
frame.getContentPane().add(lblPerson);`
I don't know how to return the String name from the ActionListener class so i obviously have an error at line 10. 我不知道如何从ActionListener类返回字符串名称,所以我显然在第10行有错误。
Just use JLabel.setText 只需使用JLabel.setText
public void actionPerformed(ActionEvent e) {
name = JOptionPane.showInputDialog("enter your name");
lblPerson.setText(name);
}
Another way you can do this is by creating (Abstract)Action inner classes in your class, which you do using JButton.setAction(MyAction); 另一种方法是通过在类中创建(Abstract)Action内部类,您可以使用JButton.setAction(MyAction);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.