Re: Passing Variable from One class to another, using an ActionListener
Jerim wrote:
What I need to happen,
is for the text of the Username and Password textboxes in the Main
Class to be sent through the Event Listener and on to the Processing
class.
There's a couple of ways to do this. The most immediate solution is to
add the text fields to the action listener so it can query them before
dispatching the processing class.
> public class ButtonListener implements ActionListener{
private JTextField password;
private JTextField username;
public ButtonListener( JTextField password, JTextField username ) {
this.password = password;
this.username = username;
}
> public void actionPerformed(ActionEvent evt){
>
> String action = evt.getActionCommand();
> if (action.equals("btnLoginClicked")){
> Processing LoginProcessing = new Processing();
> LoginProcessing.Login(username.getText(),
password.getText() );
> }
> }
> }
Then just create the ButtonListener object with the correct fields.
> public class LoginGUI {
> public static void main(String arg[]){
>
// NOTE: THIS SHOULD BE DONE ON THE EDT, NOT THE MAIN THREAD!!!
> JFrame login_frame = new JFrame();
> login_frame.setName("");
> login_frame.setSize(1024,576);
....
> JTextField txtbxUsername = new JTextField(10);
....
> JPasswordField txtbxPassword = new JPasswordField(10);
>
> JButton btnLogin = new JButton();
> btnLogin.setText("LOGIN");
> ButtonListener btnLoginListener =
new ButtonListener( txtbxPassword, txbxUsername );
> btnLogin.addActionListener(btnLoginListener);
The other way is to define an interface on the JFrame object, and use
that inside the ActionListener to get your strings. Fundamentally, it's
the same concept as what I've done here: inject the needed object into
the button listener.
Interfaces are more work because it involves more classes, more design
and conceptualization work, more moving parts to maintain, etc.
Interfaces are nicer because the result should be more testable than
using complicated classes like JTextField.
Other comments: you absolutely MUST create your Swing objects on the
EDT. The program is broken if you don't.
<http://java.sun.com/docs/books/tutorial/uiswing/concurrency/initial.html>
Also, Java by convention starts method names and field names with a
lower case letter. Login.Login() should be Login.login(), etc. Don't
use underscores in variable names (login_frame), it's considered gauche.
Don't call setName("") on a Swing component, it does nothing. I've
never had to set the opacity of a JLabel, it should work fine by default.
Good luck.