简体   繁体   中英

Java GUI Windows doesn't appear at all

I am a beginner in Java GUI. I was trying to create a simple login form in Netbeans. It consists of JFrame called TestSuiteFrame and a JPanel called TestSuiteEntryPanel containing a couple of labels, textboxes and a button. I have not yet added the "business logic".

The problem is that when I run the project, nothing happens. After a few seconds I get this as output: run: Java Result: -1073740771 BUILD SUCCESSFUL (total time: 15 seconds)

And that's it. No window appears. What exactly am I doing wrong?

Here is the code:

        package TPackage;

public class TestSuiteFrame extends javax.swing.JFrame {

    /**
     * Creates new form TestSuiteFrame
     */
    public TestSuiteFrame() {
        initComponents();
        TestSuiteEntryPanel a = new TestSuiteEntryPanel();
        add(a);


    }

    /**
     * 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() {

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>                        

    /**
     * @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(TestSuiteFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(TestSuiteFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(TestSuiteFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(TestSuiteFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        //System.out.println("abc");
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                TestSuiteFrame b = new TestSuiteFrame();
                b.setTitle("Login");
                b.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                //b.pack();
                b.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    // End of variables declaration                   
}

The Panel code:

package TPackage;
public class TestSuiteEntryPanel extends javax.swing.JPanel {

/**
 * Creates new form TestSuiteEntryPanel
 */
public TestSuiteEntryPanel() {
    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() {

    labelEntryName = new javax.swing.JLabel();
    labelEntryPassword = new javax.swing.JLabel();
    ButtonEntryLogin = new javax.swing.JButton();
    TextEntryName = new javax.swing.JTextField();
    TextEntryPassword = new javax.swing.JPasswordField();

    setPreferredSize(new java.awt.Dimension(350, 325));

    labelEntryName.setText("Name:");

    labelEntryPassword.setText("Password:");

    ButtonEntryLogin.setText("Login");

    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()
            .addGap(37, 37, 37)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                .addComponent(labelEntryPassword)
                .addComponent(labelEntryName))
            .addGap(18, 18, 18)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                .addComponent(TextEntryName, javax.swing.GroupLayout.DEFAULT_SIZE, 221, Short.MAX_VALUE)
                .addComponent(TextEntryPassword))
            .addContainerGap(24, Short.MAX_VALUE))
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(ButtonEntryLogin)
            .addGap(45, 45, 45))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(44, 44, 44)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(labelEntryName)
                .addComponent(TextEntryName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(18, 18, 18)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(labelEntryPassword)
                .addComponent(TextEntryPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(18, 18, 18)
            .addComponent(ButtonEntryLogin)
            .addContainerGap(182, Short.MAX_VALUE))
    );
}// </editor-fold>                        


// Variables declaration - do not modify                     
private javax.swing.JButton ButtonEntryLogin;
private javax.swing.JTextField TextEntryName;
private javax.swing.JPasswordField TextEntryPassword;
private javax.swing.JLabel labelEntryName;
private javax.swing.JLabel labelEntryPassword;
// End of variables declaration                   
}

Remove whole initComponents method from TestSuiteFrame class (you don't even need it) and uncomment pack within main method. It was a problem with GroupLayout . Your code should look like this:

import javax.swing.*;

public class TestSuiteFrame extends javax.swing.JFrame {

    public TestSuiteFrame() {
        TestSuiteEntryPanel a = new TestSuiteEntryPanel();
        add(a);

    }


    public static void main(String args[]) {
        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(TestSuiteFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(TestSuiteFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(TestSuiteFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(TestSuiteFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }

        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                TestSuiteFrame b = new TestSuiteFrame();
                b.setTitle("Login");
                b.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                b.pack();
                b.setVisible(true);
            }
        });
    }

}

Also, keep in mind that pack comes after you add components on JFrame . Learn how to write Java Swing code by hand and avoid use of that horrible Matisse GUI builder.

You need to invoke pack(); after all components are added to the frame. So uncommend the pack(); call above setVilisble(true); and remove the one in the constructor :- ) I Hope that helped.

Make sure you import the necessary packages (even though you probably already imported)

import java.awt.*;
import javax.swing.*;

Run your program. If nothing shows up and if you are using Windows, Press alt - tab to cycle through your opened applications.

Alternatively , after executing your program. Press ctrl + alt + del and check under the Applications tab of Windows Task Manager and see whether there exist a task by the name of Login (your java app).

I tried your codes, it does shows up a window. That JFrame from your program might be hidden by your other applications.

If you are using IDE like Netbeans, make sure the main program file is pointing to the main() within TestSuiteFrame .

If still nothing shows up, try running individual file instead of the entire project. shift + F5 or right-click TestSuiteFrame.java => run file for Netbeans.


On top of everything, make sure you are running the correct file. You can simply write some System.out.println() statements within you main() . Just check whether the console print those line when you run your program. There are many ways to check.

If the console doesn't print those println statements, then BINGO! You are probably not running the correct java file/project.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM