2013-07-10 3 views
2

Вот мой код с копией и вставкой из ошибки, которую я получаю в консоли.Что не так с моей системой входа?

package com.bob; 

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

import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JPanel; 
import javax.swing.JPasswordField; 
import javax.swing.JTextField; 

public class BobLogin extends JFrame implements ActionListener { 

    // Declare all of the component variables. 
    private JButton login; 
    private JTextField usernameField; 
    private JPasswordField passwordField; 
    private JLabel username; 
    private JLabel password; 
    private JFrame loginFrame; 

    private String usernameText = "Username:"; 
    private int usernameColumns = 20; 
    private String passwordText = "Password:"; 
    private int passwordColumns = 20; 

    //Declare all of the constants. 
    private static final int WIDTH = 300; 
    private static final int HEIGHT = 300; 

    //Login password and username. 
    private static final String correctUsername = "Admin"; 
    private static final String correctPassword = "Password"; 

    //Constructor that calls initliaziation method when an object is created. 
    public BobLogin() { 
     initializeGUI(); 
    } 

    //Sets up the login GUI. 
    private void initializeGUI() { 
     JButton login = new JButton("Login"); 
     JTextField usernameField = new JTextField(usernameColumns); 
     JPasswordField passwordField = new JPasswordField(passwordColumns); 
     JLabel username = new JLabel(usernameText); 
     JLabel password = new JLabel(passwordText); 
     JFrame loginFrame = new JFrame(); 
     JPanel loginPanel = new JPanel(new FlowLayout()); 
     loginPanel.add(username); 
     loginPanel.add(usernameField); 
     loginPanel.add(password); 
     loginPanel.add(passwordField); 
     loginPanel.add(login); 
     login.addActionListener(this); 
     loginFrame.add(loginPanel); 
     // loginFrame.setSize(WIDTH, HEIGHT); 
     loginFrame.pack(); 
     loginFrame.setLocationRelativeTo(null); 
     loginFrame.setResizable(false); 
     loginFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     loginFrame.setVisible(true); 
     //username.req 

    } 

    public static void main(String[] args) { 
     BobLogin bobLogin = new BobLogin(); 
    } 

    //What happens when the "Login" button is clicked. 
    @Override 
    public void actionPerformed(ActionEvent e) { 
     String usernameResponse = usernameField.getText(); 
     //String passwordResponse = passwordField.getText(); 
     if(usernameResponse.equalsIgnoreCase("Admin")){ 
      System.out.println("Correct"); 
     }else{ 
      System.exit(0); 
     } 
    } 

} 

Это ошибка, которую я получаю, когда попадаю в «Логин». Все работает нормально, но когда я нажимаю на кнопку входа, я получаю эту ошибку в консоли:

at com.bob.BobLogin.actionPerformed(BobLogin.java:75) 
     at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018) 
     at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341) 
     at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402) 
     at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259) 
     at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252) 
     at java.awt.Component.processMouseEvent(Component.java:6505) 
     at javax.swing.JComponent.processMouseEvent(JComponent.java:3321) 
     at java.awt.Component.processEvent(Component.java:6270) 
     at java.awt.Container.processEvent(Container.java:2229) 
     at java.awt.Component.dispatchEventImpl(Component.java:4861) 
     at java.awt.Container.dispatchEventImpl(Container.java:2287) 
     at java.awt.Component.dispatchEvent(Component.java:4687) 
     at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832) 
     at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492) 
     at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422) 
     at java.awt.Container.dispatchEventImpl(Container.java:2273) 
     at java.awt.Window.dispatchEventImpl(Window.java:2719) 
     at java.awt.Component.dispatchEvent(Component.java:4687) 
     at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:723) 
     at java.awt.EventQueue.access$200(EventQueue.java:103) 
     at java.awt.EventQueue$3.run(EventQueue.java:682) 
     at java.awt.EventQueue$3.run(EventQueue.java:680) 
     at java.security.AccessController.doPrivileged(Native Method) 
     at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76) 
     at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87) 
     at java.awt.EventQueue$4.run(EventQueue.java:696) 
     at java.awt.EventQueue$4.run(EventQueue.java:694) 
     at java.security.AccessController.doPrivileged(Native Method) 
     at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76) 
     at java.awt.EventQueue.dispatchEvent(EventQueue.java:693) 
     at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242) 
     at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161) 
     at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150) 
     at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146) 
     at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138) 
     at java.awt.EventDispatchThread.run(EventDispatchThread.java:91) 
+0

@trashgod Я новичок здесь, не знал этого! Спасибо вам, сэр! –

ответ

3

Вы используете экземпляр переменной usernameField, чтобы получить текст, когда ActionEvent срабатывает. Проблема в том, что вы создаете новую локальную переменную usernameField внутри вашего метода initializeGUI, пока она уже создана как переменная экземпляра, но она не инициализирована. Чтобы исправить вашу проблему, инициализируйте переменную usernameField вне метода initializeGUI. Это работает код:

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

import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JPanel; 
import javax.swing.JPasswordField; 
import javax.swing.JTextField; 

public class BobLogin extends JFrame implements ActionListener { 

    // Declare all of the component variables. 
    private JButton login; 
    //Here is an issue fix! 
    private JTextField usernameField = new JTextField(20); 
    private JPasswordField passwordField = new JPasswordField(20);; 
    private JLabel username; 
    private JLabel password; 
    private JFrame loginFrame; 

    private String usernameText = "Username:"; 
    private int usernameColumns = 20; 
    private String passwordText = "Password:"; 
    private int passwordColumns = 20; 

    //Declare all of the constants. 
    private static final int WIDTH = 300; 
    private static final int HEIGHT = 300; 

    //Login password and username. 
    private static final String correctUsername = "Admin"; 
    private static final String correctPassword = "Password"; 

    //Constructor that calls initliaziation method when an object is created. 
    public BobLogin() { 
     initializeGUI(); 
    } 

    //Sets up the login GUI. 
    private void initializeGUI() { 
     JButton login = new JButton("Login"); 
     JLabel username = new JLabel(usernameText); 
     JLabel password = new JLabel(passwordText); 
     JFrame loginFrame = new JFrame(); 
     JPanel loginPanel = new JPanel(new FlowLayout()); 
     loginPanel.add(username); 
     loginPanel.add(usernameField); 
     loginPanel.add(password); 
     loginPanel.add(passwordField); 
     loginPanel.add(login); 
     login.addActionListener(this); 
     loginFrame.add(loginPanel); 
     // loginFrame.setSize(WIDTH, HEIGHT); 
     loginFrame.pack(); 
     loginFrame.setLocationRelativeTo(null); 
     loginFrame.setResizable(false); 
     loginFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     loginFrame.setVisible(true); 
     //username.req 

    } 

    public static void main(String[] args) { 
     BobLogin bobLogin = new BobLogin(); 
    } 

    //What happens when the "Login" button is clicked. 
    @Override 
    public void actionPerformed(ActionEvent e) { 
     String usernameResponse = usernameField.getText(); 
     //String passwordResponse = passwordField.getText(); 
     if(usernameResponse.equalsIgnoreCase("Admin")){ 
      System.out.println("Correct"); 
     }else{ 
      System.exit(0); 
     } 
    } 

} 
+0

Большое вам спасибо! Это все! Еще раз спасибо!!! –

2

У вас есть эта строка в вашем Initialize() метод

JTextField usernameField = new JTextField(usernameColumns); 

Который фактически создает локальный экземпляр usernameField.

Попробуйте

usernameField = new JTextField(usernameColumns); 

инициализировать переменную класса.

Эта концепция также относится к нескольким другим переменным класса, которые вы указали.

+0

Это исправлено. Спасибо, что помогли человеку! –

Смежные вопросы