Reputation: 616
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.
Upvotes: 0
Views: 615
Reputation: 35011
Just use 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);
Upvotes: 2