Java:在swing窗口等待用户输入

时间:2016-03-17 19:38:09

标签: java swing oop

所以,我在一周前开始学习java,我遇到了一些问题,我正在建设一个小程序来训练swing和oop / java。

程序(到目前为止)有一个MainClass和一个Window类。 MainClass创建一个Window类的实例,它创建一个JFrame并将用户输入保存在一个字段中。

此时,MainClass打印输出,我通过getter方法获得输出。

问题在于我仍然以程序的方式思考:MainClass打印null,因为它不等待窗口的istance来获取用户输入。

如何修复它,从而在打印之前主要等待窗口接受用户输入?

的Nb。 Jframe的东西工作,窗口出现,只是MainClass不等待它做它应该做的事情。我可以(我认为?)使用一些睡眠命令等待,但它似乎完全错了。

这是MainClass.java的代码

import java.util.Arrays;

public class MainClass {

    private char[] password;
    private String pin;

    public static void main(String[] args) {

        Window w = new Window();    
        System.out.println(w.getPin() + Arrays.toString(w.getPassword()) + '1');
    }


}

和Window.java

import java.awt.*;
import javax.swing.*;
import java.awt.Window.Type;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;

import net.miginfocom.swing.MigLayout;


public class Window extends JFrame{

    private JTextField textField_1;
    private JButton btnNewButton;
    private JPanel panel;
    private JPasswordField passwordField;
    private char[] password = new char[10];
    private String pin;


    public Window() {

        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLocationRelativeTo(null);
        this.setSize(370, 150);
        this.setForeground(new Color(192, 192, 192));
        this.setTitle("Access Password Manager");
        this.setResizable(false);

        panel = new JPanel();
        getContentPane().add(panel, BorderLayout.CENTER);
        panel.setLayout(new MigLayout("", "[70.00][132.00,grow][44.00][67.00,grow][61.00][]", "[19.00][34.00][]"));

        JLabel lblNewLabel = new JLabel("Password");
        panel.add(lblNewLabel, "cell 0 1,alignx trailing,aligny center");

        passwordField = new JPasswordField();
        passwordField.setColumns(13);
        panel.add(passwordField, "cell 1 1,alignx center");

        JLabel lblNewLabel_1 = new JLabel("Key");
        panel.add(lblNewLabel_1, "cell 2 1,alignx center,aligny center");

        textField_1 = new JTextField();
        panel.add(textField_1, "cell 3 1,alignx left,aligny center");
        textField_1.setColumns(4);

        btnNewButton = new JButton("Log In");
        ListenForButton listener = new ListenForButton();

        btnNewButton.addActionListener(listener);
        panel.add(btnNewButton, "cell 4 1");

        this.setVisible(true);

    }

        private class ListenForButton implements ActionListener{


            @Override
            public void actionPerformed(ActionEvent e) {

                if(e.getSource() == btnNewButton){

                    if (passwordField.getPassword().length < 10){

                        password = passwordField.getPassword().clone();   
                    }

                    pin = textField_1.getText();

                }
            }       
        }


        public char[] getPassword(){            
            return password;            
        }

        public String getPin(){
            return pin;     
        }


}

编辑:

这不仅仅是打印,我知道我可以直接进入Window.class。 如果我解释不好,我很抱歉。请将println视为“我需要在窗口保存输入后访问和处理这些字段”。

3 个答案:

答案 0 :(得分:3)

您可以使用模态对话框来获取用户输入,该对话框将阻止代码在可见时执行,并在其变为不可见时继续执行(这很神奇),请查看How to Make Dialogs以获取更多信息细节

<强>更新

模态对话框只会阻止事件调度线程(技术上它不会阻止它,它只是绕过它),有关更多详细信息,请参阅Initial Threads

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import net.miginfocom.swing.MigLayout;

public class MainClass {

    private char[] password;
    private String pin;

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                System.out.println("Before Window");
                Window w = new Window();
                System.out.println("After Window");
                System.out.println(w.getPin() + Arrays.toString(w.getPassword()) + '1');
            }
        });
    }

    public static class Window extends JDialog {

        private JTextField textField_1;
        private JButton btnNewButton;
        private JPanel panel;
        private JPasswordField passwordField;
        private char[] password = new char[10];
        private String pin;

        public Window() {

            this.setModal(true);
            this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            this.setLocationRelativeTo(null);
            this.setSize(370, 150);
            this.setForeground(new Color(192, 192, 192));
            this.setTitle("Access Password Manager");
            this.setResizable(false);

            panel = new JPanel();
            getContentPane().add(panel, BorderLayout.CENTER);
            panel.setLayout(new MigLayout("", "[70.00][132.00,grow][44.00][67.00,grow][61.00][]", "[19.00][34.00][]"));

            JLabel lblNewLabel = new JLabel("Password");
            panel.add(lblNewLabel, "cell 0 1,alignx trailing,aligny center");

            passwordField = new JPasswordField();
            passwordField.setColumns(13);
            panel.add(passwordField, "cell 1 1,alignx center");

            JLabel lblNewLabel_1 = new JLabel("Key");
            panel.add(lblNewLabel_1, "cell 2 1,alignx center,aligny center");

            textField_1 = new JTextField();
            panel.add(textField_1, "cell 3 1,alignx left,aligny center");
            textField_1.setColumns(4);

            btnNewButton = new JButton("Log In");
            ListenForButton listener = new ListenForButton();

            btnNewButton.addActionListener(listener);
            panel.add(btnNewButton, "cell 4 1");

            this.setVisible(true);

        }

        private class ListenForButton implements ActionListener {

            @Override
            public void actionPerformed(ActionEvent e) {

                if (e.getSource() == btnNewButton) {

                    if (passwordField.getPassword().length < 10) {

                        password = passwordField.getPassword().clone();
                    }

                    pin = textField_1.getText();

                }
            }
        }

        public char[] getPassword() {
            return password;
        }

        public String getPin() {
            return pin;
        }

    }
}

答案 1 :(得分:1)

如果您希望在按钮单击时打印结果,则可以在按钮的动作侦听器中打印它。如果您希望在用户输入任何内容后立即打印它,您可以将动作侦听器添加到您的密码文本字段。

窗口/视图

public class Window extends JFrame{

  private Controller controller;
  private Model model;

  public Window(Controller controller, Model model) {
    this.controller = controller;
    this.model = model;
  }

模型

public class Model {

  private String password;
  //getters and setters
}

控制器

public class Controller {

  public void doSomething() {
    // do anything. Views could invoke controller methods to do things and is usually invoked when certain events happen.
  }

主要

public class Main {

  public static void main(String[] args) {
    new Window(new Controller(), new Model());
  }

答案 2 :(得分:0)

你应该使用活动。如果按下窗口中的按钮,您的主类可以监听事件。 e.g。

public static void main(String[] args) {
   Window w = new Window();  
   w.getBtnNewButton().addActionListener(new ActionListener(){
      @Override
      public void actionPerformed(ActionEvent e) {
         System.out.println(w.getPin() + Arrays.toString(w.getPassword()) +  '1');
      }
   });  
}

在这种情况下,您必须为按钮创建一个公共getter,以便您可以从主类访问它。