user1000232
user1000232

Reputation: 219

Get input from JFrame

I am a little bit confused on exactly how to program this. I have a class extending JFrame with two textfields. I want to be able to get input from JFrame. Somehow just wait for the input from my mainMaybe class...Any ideas?

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JTextField;


public class mainMaybe extends JFrame{
    JTextField login;
    JTextField pass;

    public mainMaybe() throws InterruptedException{
        login = new JTextField();
        pass = new JTextField();
        pass.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent arg0) {
                 System.out.println("DO SOMETHING");
            }       
        });
        add(login,BorderLayout.NORTH);
        add(pass,BorderLayout.SOUTH);
        pack();
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public void returnEmail(){
        //SOME HOW WAIT FOR THE ACTION LISTENER?
    }

    public static void main(String[] args) throws InterruptedException {
        new mainMaybe().returnEmail(); 
        //CONTROL SHOULD STAY WITH mainMaybe until an email is returned         
    }

}

Upvotes: 2

Views: 45732

Answers (3)

Sujay
Sujay

Reputation: 6783

Java Swing is based on the concept of event-driven architecture. As such, events trigger actions and based on these events you would perform some kind of operation.

Using Swing Component would be a good point to start to understand and consequently implement what you want to achieve in terms of your UI and its corresponding behavior. So I would suggest that you read a bit about it and then try to tackle what you're trying to achieve.

I'm not so sure of what you're trying to achieve but if I were you, I would have two text fields, maybe some labels attached to it and a "Submit" button. And I would add an ActionListener to this button to perform some kind of action.

Maybe an SSCCE might help you get started. So have a look at this code:

package com.test;

import javax.swing.JOptionPane;

public class SimpleUI extends javax.swing.JFrame {

    /**
     * Creates new form SimpleUI
     */
    public SimpleUI() {
        initComponents();
    }

    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        labelName = new javax.swing.JLabel();
        textName = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        textPassword = new javax.swing.JPasswordField();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        mainPanel.setBorder(javax.swing.BorderFactory.createEmptyBorder(2, 2, 2, 2));

        labelName.setText("Name: ");

        jLabel1.setText("Password: ");

        jButton1.setText("Submit");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(labelName)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(textName)
                    .addComponent(textPassword, javax.swing.GroupLayout.DEFAULT_SIZE, 195, Short.MAX_VALUE))
                .addGap(18, 18, 18)
                .addComponent(jButton1)
                .addGap(0, 65, Short.MAX_VALUE))
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(labelName)
                    .addComponent(textName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(textPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addContainerGap(15, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(mainPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(mainPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pack();
    }


    /**
    *   This is the method that is called when an action is performed.
    *   Over here I just simply show an error message if any of the text fields are empty or just show their names.
    */
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        String name         = textName.getText();
        String password     = String.valueOf(textPassword.getPassword());

        if("".equals(password) || "".equals(name)){
            JOptionPane.showMessageDialog(this, "Name or password is empty!", "Incorrect Input", JOptionPane.ERROR_MESSAGE);
        }else{
            JOptionPane.showMessageDialog(this, "Hello "+name+" with password "+password, "Incorrect Input", JOptionPane.PLAIN_MESSAGE);
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {

        try {
            javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(SimpleUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(SimpleUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(SimpleUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(SimpleUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }


        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new SimpleUI().setVisible(true);
            }
        });
    }

    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel labelName;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JTextField textName;
    private javax.swing.JPasswordField textPassword;

}

Note: I generated this code using NetBeans IDE, so I didn't have to handle much about the layout or anything. If you want to learn about Layouts, here's an interesting tutorial: "A Visual Guide to Layout Managers"

The main idea for me was to show you how events are triggered. So what I did was I added an actionlistener to my "Submit" button and when someone clicks on the button, I perform some kind of action. Hope you get the picture.

Upvotes: 8

Andrew Thompson
Andrew Thompson

Reputation: 168825

Alternate approach, using a modal dialog (or rather, two of them).

import javax.swing.*;

public class LoginPrompt {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                String username = JOptionPane.showInputDialog(null, "User Name");
                System.out.println("Username: " + username);

                JPasswordField passwordField = new JPasswordField(8);
                // a bit quirky, we need to tab to the field
                JOptionPane.showMessageDialog(null, passwordField, "Password",
                        JOptionPane.QUESTION_MESSAGE);
                char[] password = null;
                password = passwordField.getPassword();
                System.out.println("Password: " + String.valueOf(password));
            }
        });
    }
}

Upvotes: 3

John3136
John3136

Reputation: 29266

I think you have your design approach wrong. In Java GUIs (and most similar technologies), you don't say "wait for an email address" you say "tell me when you get an email address".

You're part way there with adding a listener to the text box - basically you want a listener that will "fire" when the value in the texbox is changed. The listener's implementation does something - in you simple example, writes the email address to the consol then exits.

Upvotes: 4

Related Questions