0

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.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
T4l0n
  • 595
  • 1
  • 8
  • 25
  • Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). – Andrew Thompson May 29 '15 at 14:26

1 Answers1

2

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);

ControlAltDel
  • 33,923
  • 10
  • 53
  • 80