0

I am new to Java and have what could be a newbies problem. I am trying to call a jframe from another. In this case there is a login jframe and then an admin jframe that I want to get to work when I login.

The login is :

    package masterdocument;

import java.sql.*;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import oracle.jdbc.OraclePreparedStatement;
import oracle.jdbc.OracleResultSet;
import java.lang.*;


public class Login extends javax.swing.JFrame {

Connection conn=null;
OraclePreparedStatement pst=null;
OracleResultSet rs=null;

/**
 * Creates new form Login
 */
public Login() {
    initComponents();
}
 ...
     private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    // TODO add your handling code here:

    conn = JavaConnectDB.ConnecrDB();
    try{
        String sql="select * from tutilizadores where username= ? and password= ?";
        PreparedStatement pst = conn.prepareStatement(sql);
        pst.setString(1, USERNAME.getText());
        pst.setString(2, PASSWORD.getText());
        rs=(OracleResultSet)pst.executeQuery();
        if (rs.next()){
        //JOptionPane.showMessageDialog(null, "O username e password estavam bem");
        //Fecha a janela
        //close();

        //nova janela-Tutilizadores
        Tutilizadores c = new Tutilizadores();
        c.setVisible(true);
        }
        else{
        JOptionPane.showMessageDialog(null, "Login Inválido");
        }

    } catch(Exception e){
                        JOptionPane.showMessageDialog(null,e);
    }

}                                        

and the Tutilizadores is :

    package masterdocument;

import java.awt.EventQueue;
import java.beans.Beans;
import java.util.ArrayList;

import java.util.List;
import javax.persistence.RollbackException;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Tutilizadores extends JPanel {

public Tutilizadores() {
    initComponents();
    if (!Beans.isDesignTime()) {
        entityManager.getTransaction().begin();
    }
}

/**
 * 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() {
    bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

    entityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("jdbc:oracle:thin:@localhost:1521:db01PU").createEntityManager();
    query = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT t FROM Tutilizadores_1 t");
    list = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(query.getResultList());
    masterScrollPane = new javax.swing.JScrollPane();
    masterTable = new javax.swing.JTable();
    utilIdLabel = new javax.swing.JLabel();
    usernameLabel = new javax.swing.JLabel();
    passwordLabel = new javax.swing.JLabel();
    perfilLabel = new javax.swing.JLabel();
    utilIdField = new javax.swing.JTextField();
    usernameField = new javax.swing.JTextField();
    passwordField = new javax.swing.JTextField();
    perfilField = new javax.swing.JTextField();
    saveButton = new javax.swing.JButton();
    refreshButton = new javax.swing.JButton();
    newButton = new javax.swing.JButton();
    deleteButton = new javax.swing.JButton();

    FormListener formListener = new FormListener();

    org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, list, masterTable);
    org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${utilId}"));
    columnBinding.setColumnName("Util Id");
    columnBinding.setColumnClass(java.math.BigDecimal.class);
    columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${username}"));
    columnBinding.setColumnName("Username");
    columnBinding.setColumnClass(String.class);
    columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${password}"));
    columnBinding.setColumnName("Password");
    columnBinding.setColumnClass(String.class);
    columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${perfil}"));
    columnBinding.setColumnName("Perfil");
    columnBinding.setColumnClass(java.math.BigInteger.class);
    bindingGroup.addBinding(jTableBinding);

    masterScrollPane.setViewportView(masterTable);

    utilIdLabel.setText("Util Id:");

    usernameLabel.setText("Username:");

    passwordLabel.setText("Password:");

    perfilLabel.setText("Perfil:");

    org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.utilId}"), utilIdField, org.jdesktop.beansbinding.BeanProperty.create("text"));
    binding.setSourceUnreadableValue("null");
    bindingGroup.addBinding(binding);
    binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), utilIdField, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
    bindingGroup.addBinding(binding);

    binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.username}"), usernameField, org.jdesktop.beansbinding.BeanProperty.create("text"));
    binding.setSourceUnreadableValue("null");
    bindingGroup.addBinding(binding);
    binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), usernameField, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
    bindingGroup.addBinding(binding);

    binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.password}"), passwordField, org.jdesktop.beansbinding.BeanProperty.create("text"));
    binding.setSourceUnreadableValue("null");
    bindingGroup.addBinding(binding);
    binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), passwordField, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
    bindingGroup.addBinding(binding);

    binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.perfil}"), perfilField, org.jdesktop.beansbinding.BeanProperty.create("text"));
    binding.setSourceUnreadableValue("null");
    bindingGroup.addBinding(binding);
    binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), perfilField, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
    bindingGroup.addBinding(binding);

    saveButton.setText("Save");
    saveButton.addActionListener(formListener);

    refreshButton.setText("Refresh");
    refreshButton.addActionListener(formListener);

    newButton.setText("New");
    newButton.addActionListener(formListener);

    deleteButton.setText("Delete");

    binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), deleteButton, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
    bindingGroup.addBinding(binding);

    deleteButton.addActionListener(formListener);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
    this.setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addComponent(newButton)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(deleteButton)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(refreshButton)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(saveButton)
            .addContainerGap())
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(utilIdLabel)
                .addComponent(usernameLabel)
                .addComponent(passwordLabel)
                .addComponent(perfilLabel))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(utilIdField, javax.swing.GroupLayout.DEFAULT_SIZE, 315, Short.MAX_VALUE)
                .addComponent(usernameField, javax.swing.GroupLayout.DEFAULT_SIZE, 315, Short.MAX_VALUE)
                .addComponent(passwordField, javax.swing.GroupLayout.DEFAULT_SIZE, 315, Short.MAX_VALUE)
                .addComponent(perfilField, javax.swing.GroupLayout.DEFAULT_SIZE, 315, Short.MAX_VALUE))
            .addContainerGap())
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(masterScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
            .addContainerGap())
    );

    layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {deleteButton, newButton, refreshButton, saveButton});

    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(masterScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 130, Short.MAX_VALUE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(utilIdLabel)
                .addComponent(utilIdField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(usernameLabel)
                .addComponent(usernameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(passwordLabel)
                .addComponent(passwordField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(perfilLabel)
                .addComponent(perfilField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(saveButton)
                .addComponent(refreshButton)
                .addComponent(deleteButton)
                .addComponent(newButton))
            .addContainerGap())
    );

    bindingGroup.bind();
}

// Code for dispatching events from components to event handlers.

private class FormListener implements java.awt.event.ActionListener {
    FormListener() {}
    public void actionPerformed(java.awt.event.ActionEvent evt) {
        if (evt.getSource() == saveButton) {
            Tutilizadores.this.saveButtonActionPerformed(evt);
        }
        else if (evt.getSource() == refreshButton) {
            Tutilizadores.this.refreshButtonActionPerformed(evt);
        }
        else if (evt.getSource() == newButton) {
            Tutilizadores.this.newButtonActionPerformed(evt);
        }
        else if (evt.getSource() == deleteButton) {
            Tutilizadores.this.deleteButtonActionPerformed(evt);
        }
    }
}// </editor-fold>                        



@SuppressWarnings("unchecked")
private void refreshButtonActionPerformed(java.awt.event.ActionEvent evt) {                                              
    entityManager.getTransaction().rollback();
    entityManager.getTransaction().begin();
    java.util.Collection data = query.getResultList();
    for (Object entity : data) {
        entityManager.refresh(entity);
    }
    list.clear();
    list.addAll(data);
}                                             

private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {                                             
    int[] selected = masterTable.getSelectedRows();
    List<masterdocument.Tutilizadores_1> toRemove = new ArrayList<masterdocument.Tutilizadores_1>(selected.length);
    for (int idx = 0; idx < selected.length; idx++) {
        masterdocument.Tutilizadores_1 t = list.get(masterTable.convertRowIndexToModel(selected[idx]));
        toRemove.add(t);
        entityManager.remove(t);
    }
    list.removeAll(toRemove);
}                                            

private void newButtonActionPerformed(java.awt.event.ActionEvent evt) {                                          
    masterdocument.Tutilizadores_1 t = new masterdocument.Tutilizadores_1();
    entityManager.persist(t);
    list.add(t);
    int row = list.size() - 1;
    masterTable.setRowSelectionInterval(row, row);
    masterTable.scrollRectToVisible(masterTable.getCellRect(row, 0, true));
}                                         

private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {                                           
    try {
        entityManager.getTransaction().commit();
        entityManager.getTransaction().begin();
    } catch (RollbackException rex) {
        rex.printStackTrace();
        entityManager.getTransaction().begin();
        List<masterdocument.Tutilizadores_1> merged = new ArrayList<masterdocument.Tutilizadores_1>(list.size());
        for (masterdocument.Tutilizadores_1 t : list) {
            merged.add(entityManager.merge(t));
        }
        list.clear();
        list.addAll(merged);
    }


}                                          



// Variables declaration - do not modify                     
private javax.swing.JButton deleteButton;
private javax.persistence.EntityManager entityManager;
private java.util.List<masterdocument.Tutilizadores_1> list;
private javax.swing.JScrollPane masterScrollPane;
private javax.swing.JTable masterTable;
private javax.swing.JButton newButton;
private javax.swing.JTextField passwordField;
private javax.swing.JLabel passwordLabel;
private javax.swing.JTextField perfilField;
private javax.swing.JLabel perfilLabel;
private javax.persistence.Query query;
private javax.swing.JButton refreshButton;
private javax.swing.JButton saveButton;
private javax.swing.JTextField usernameField;
private javax.swing.JLabel usernameLabel;
private javax.swing.JTextField utilIdField;
private javax.swing.JLabel utilIdLabel;
private org.jdesktop.beansbinding.BindingGroup bindingGroup;
// End of variables declaration                   





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(Tutilizadores.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(Tutilizadores.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(Tutilizadores.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(Tutilizadores.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
     EventQueue.invokeLater(new Runnable() {
        public void run() {
            JFrame frame = new JFrame();
            frame.setContentPane(new Tutilizadores());
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setVisible(true);
        }
    });

}

}

why is this not working ? Thank you in advance!!

AlexG
  • 11
  • 5
  • 1) See [The Use of Multiple JFrames, Good/Bad Practice?](http://stackoverflow.com/q/9554636/418556) 2) For better help sooner, post an [MCVE](http://stackoverflow.com/help/mcve) (Minimal Complete Verifiable Example) or [SSCCE](http://www.sscce.org/) (Short, Self Contained, Correct Example). (No external dependencies self contained.) – Andrew Thompson May 25 '15 at 10:05
  • Thank you ! For now I will have to do this so I am stuck with bad practice. – AlexG May 25 '15 at 10:09
  • 1
    *"I am trying to call a jframe from another"* is probably your first mistake. You might like to use a modal dialog instead. Have a look at [How to Make Dialogs](http://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html) for more details – MadProgrammer May 25 '15 at 10:25
  • `Tutilizadores` isn't a frame/window, it – MadProgrammer May 25 '15 at 10:27

2 Answers2

3

Tutilizadores isn't a frame/window, it's a JPanel, it can't be shown on the screen without some kind of window container to display it

See Top level containers and How to make frames (main windows) for more details.

Now having said that, you are in a great position to make use of a CardLayout which would allow you to change the views from you "login" view to you "admin" view within the same window (although you might need to refactor the login window to use a JPanel instead of a JFrame)

Take a look at How to Use CardLayout for more details.

You should probably also take a look at How to Make Dialogs which provides an alternative soultion

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
0

Add this class, it will wrap your Tuttilizadores JPanel in a JFrame. Because you can't just dipslay JPanel, it can be drawn only on some surface, like JFrame.

    import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;


public class TuttilizadoresFrame extends JFrame {


    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    TuttilizadoresFrame window = new TuttilizadoresFrame();
                    window.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public TuttilizadoresFrame() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        setBounds(100, 100, 450, 300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        Tutilizadores tutilizadores = new Tutilizadores();
        getContentPane().add(tutilizadores, BorderLayout.CENTER);
    }

}

then change the creation of Tuttilizadores to TuttilizadoresFrame

change line Tutilizadores c = new Tutilizadores(); in the Login class,to:

TuttilizadoresFrame c = new TuttilizadoresFrame();

Krzysztof Cichocki
  • 6,294
  • 1
  • 16
  • 32
  • If I do that I get java.lang.IllegalArgumentException: GroupLayout can only be used with on container at a time. – AlexG May 25 '15 at 10:16
  • 1
    *"Add this class:"* - But why? Dumping a bunch of code onto a poster without an explanation of "why" they should use it doesn't really help them or anybody else – MadProgrammer May 25 '15 at 10:24
  • If someone is a thinking human, then he will catch the answer from it. One picture is worth more than a thousand words. – Krzysztof Cichocki May 25 '15 at 10:29