2

我对如何编程有点困惑。我有一个用两个文本字段扩展 JFrame 的类。我希望能够从 JFrame 获取输入。不知何故,只是等待我的 mainMaybe 类的输入......有什么想法吗?

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         
    }

}
4

3 回答 3

8

Java Swing 基于event-driven architecture. 因此,事件会触发操作,并且基于这些事件,您将执行某种操作。

使用 Swing 组件将是一个很好的起点,可以开始理解并实现您想要在 UI 及其相应行为方面实现的目标。所以我建议你阅读一下它,然后尝试解决你想要实现的目标。

我不太确定您要实现的目标,但如果我是您,我将有两个文本字段,可能会附加一些标签和一个“提交”按钮。我会在ActionListener这个按钮上添加一个来执行某种操作。

也许SSCCE可以帮助您入门。所以看看这段代码:

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;

}

注意:我使用 NetBeans IDE 生成了这段代码,所以我不需要处理太多关于布局或任何事情的事情。如果你想了解 Layouts,这里有一个有趣的教程:“A Visual Guide to Layout Managers”

我的主要想法是向您展示事件是如何触发的。所以我所做的就是actionlistener在我的“提交”按钮中添加了一个,当有人点击该按钮时,我会执行某种操作。希望你能得到图片。

于 2012-08-13T03:53:24.200 回答
4

我认为您的设计方法错误。在 Java GUI(和大多数类似技术)中,您不会说“等待电子邮件地址”,而是说“当您收到电子邮件地址时告诉我”。

您已经向文本框添加了一个侦听器 - 基本上您想要一个在 texbox 中的值更改时会“触发”的侦听器。侦听器的实现做了一些事情 - 在你的简单示例中,将电子邮件地址写入控制台然后退出。

于 2012-08-13T03:52:32.387 回答
3

另一种方法,使用模态对话框(或者更确切地说,其中两个)。

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));
            }
        });
    }
}
于 2012-08-13T04:21:29.870 回答