java 摆动,从 ActionListener 获取值
java swing, get value from ActionListener
我想点击一个按钮并弹出一个 window,我可以在其中输入一个字符串,该字符串将在标签中输出,但我无法做到 return字符串。
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);`
我不知道如何 return 来自 ActionListener 的字符串名称 class 所以我显然在第 10 行有一个错误。
只需使用JLabel.setText
public void actionPerformed(ActionEvent e) {
name = JOptionPane.showInputDialog("enter your name");
lblPerson.setText(name);
}
另一种方法是在 class 中创建 (Abstract)Action inner classes,使用 JButton.setAction(MyAction);
我想点击一个按钮并弹出一个 window,我可以在其中输入一个字符串,该字符串将在标签中输出,但我无法做到 return字符串。
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);`
我不知道如何 return 来自 ActionListener 的字符串名称 class 所以我显然在第 10 行有一个错误。
只需使用JLabel.setText
public void actionPerformed(ActionEvent e) {
name = JOptionPane.showInputDialog("enter your name");
lblPerson.setText(name);
}
另一种方法是在 class 中创建 (Abstract)Action inner classes,使用 JButton.setAction(MyAction);