I'm trying to learn Swing and JFrame, so I'm creating a really simple program that asks for your name and then displays a box telling you what you've entered. I'm trying to use a separate class from the first to act as the ActionListener and display the name that was typed in. However it's not working for me. I tried creating a constructor in the second class that sets an instance variable to the value taken in the JTextfield but it's not showing up as I expected. Please have a look;
And here's my code (I've imported all libraries properly but omitted for space's sake)
This is the main class...
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);
}
}
And this is the ActionListener class:
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 );
}
}