У меня есть несколько JFrames, между которыми я хочу переключаться нажатием кнопки.
Вот мой код для моего фрейма входа (без автоматически сгенерированного кода, созданного NetBeans)
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package mzamomstha.registration;
import javax.swing.JFrame;
/**
*
* @author Enzo
*/
public class Login extends javax.swing.JFrame {
public LearnerDatabase learnerDatabaseFrame;
public void setLearnerDatabase (LearnerDatabase learnerDatabaseFrame) {
this.learnerDatabaseFrame = learnerDatabaseFrame;
}
public void openLearnerDataBase() {
Login
new LearnerDatabase().setVisible(true);
}
public TeacherDatabase teacherDatabase;
public void setTeacherDatabase (TeacherDatabase teacherDatabase) {
this.teacherDatabase = teacherDatabase;
}
public void openTeacherDatabase() {
teacherDatabase.setVisible(true);
}
public ParentDatabase parentDatabase;
public void setParentDatabase (ParentDatabase parentDatabase) {
this.parentDatabase = parentDatabase;
}
public void openParentDatabase() {
parentDatabase.setVisible(true);
}
/**
* Creates new form Login
*/
public Login() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
edtUsername = new javax.swing.JTextField();
edtPassword = new javax.swing.JPasswordField();
btnLogin = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Login Frame");
setName("loginFrame"); // NOI18N
jLabel1.setText("Username:");
jLabel2.setText("Password:");
btnLogin.setText("Login");
btnLogin.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnLoginActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(35, 35, 35)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel2)
.addGap(100, 100, 100)
.addComponent(edtPassword))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(100, 100, 100)
.addComponent(edtUsername, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGroup(layout.createSequentialGroup()
.addGap(130, 130, 130)
.addComponent(btnLogin)))
.addContainerGap(35, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(35, 35, 35)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(edtUsername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(30, 30, 30)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(jLabel2)
.addComponent(edtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(30, 30, 30)
.addComponent(btnLogin)
.addContainerGap(35, Short.MAX_VALUE))
);
getAccessibleContext().setAccessibleName("loginFrame");
pack();
}// </editor-fold>
private void btnLoginActionPerformed(java.awt.event.ActionEvent evt) {
boolean parentLogin = false;
boolean teacherLogin = false;
boolean adminLogin = false;
boolean learnerLogin = false;
String username = edtUsername.getText();
String password = edtPassword.getText();
//Leaner Login Details
if (username.equals("Enzo") && password.equals("EnzoPassword")) {
learnerLogin = true;
}
//Parent Login Details
if (username.equals("Sharon") && password.equals("SharonPassword")) {
parentLogin = true;
}
//Teacher Login Details
if (username.equals("Karl") && password.equals("KarlPassword")) {
teacherLogin = true;
}
//Admin Login Details
if (username.equals("Michael") && password.equals("MichaelPassword")) {
adminLogin = true;
}
if (learnerLogin) {
openLearnerDataBase();
}
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Login().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton btnLogin;
private javax.swing.JPasswordField edtPassword;
private javax.swing.JTextField edtUsername;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
// End of variables declaration
}
Когда я нажимаю btnLogin, я хочу иметь возможность отображать мою LearnerDataBase, TeacherDataBase или ParentDatabase (это имена фреймов, я назвал их так, потому что на них есть таблицы, которые будут отображать мои базы данных) в зависимости от имя пользователя и пароль, которые они вводят. И, конечно же, «детали» ученика, учителя и родителя будут изменены, чтобы соответствовать базе данных, это просто для проверки.
При необходимости я также могу добавить свой код других фреймов.
С этим кодом я получаю «Исключение в потоке» AWT-EventQueue-0 »java .lang.NullPointerException« Ошибка.
Это моя трассировка стека
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at mzamomstha.registration.Login.openLearnerDataBase(Login.java:21)
at mzamomstha.registration.Login.btnLoginActionPerformed(Login.java:151)
at mzamomstha.registration.Login.access$000(Login.java:12)
at mzamomstha.registration.Login$1.actionPerformed(Login.java:79)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
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:6539)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
at java.awt.Component.processEvent(Component.java:6304)
at java.awt.Container.processEvent(Container.java:2239)
at java.awt.Component.dispatchEventImpl(Component.java:4889)
at java.awt.Container.dispatchEventImpl(Container.java:2297)
at java.awt.Component.dispatchEvent(Component.java:4711)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4904)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4535)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4476)
at java.awt.Container.dispatchEventImpl(Container.java:2283)
at java.awt.Window.dispatchEventImpl(Window.java:2746)
at java.awt.Component.dispatchEvent(Component.java:4711)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:760)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:84)
at java.awt.EventQueue$4.run(EventQueue.java:733)
at java.awt.EventQueue$4.run(EventQueue.java:731)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:730)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:205)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
СОЗДАТЬ УСПЕШНО (общее время: 8 секунд)
Кроме того, я только учусь этому, поэтому не знаю всех причудливых техник.