简体   繁体   中英

How to use autogenerated netbeans JFrame forms?

I want to develop a mini game and I struggle creating a Menu for this app. The Menu consists of 3 buttons (exit, rules, play) and I want to let the netbeans JFrame form designer to take care of it (you know, I just place the buttons, assign them functionality and style and the IDE creates the class code for me). Now, the problem is that I do not know how to implement this code. It says that "This method is called from within the constructor to initialize the form.", so I guessed that I just had to do:

public Menu() {
        create_and_show_menu();
    }    

private void create_and_show_menu() {
JFrame f = new JFrame("Menu");
    new Sterge();
    f.setExtendedState(JFrame.MAXIMIZED_BOTH);
    f.setLayout(null);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setLocationRelativeTo(null);
    f.setVisible(true);
}

... but it didn't work out. Please tell me how to use that freakin' JFrame form, cause I haven't found anything online about that.

The auto-generated class code:

/*
 * 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.
 */

/**
 *
 * @author stoic
 */
public class Sterge extends javax.swing.JFrame {

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

        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("jButton1");
        jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                jButton1MousePressed(evt);
            }
        });

        jButton2.setText("jButton1");
        jButton2.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                jButton2MousePressed(evt);
            }
        });

        jButton3.setText("jButton1");
        jButton3.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                jButton3MousePressed(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()
                .addGap(138, 138, 138)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton1)
                    .addComponent(jButton2)
                    .addComponent(jButton3))
                .addContainerGap(189, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(75, 75, 75)
                .addComponent(jButton1)
                .addGap(42, 42, 42)
                .addComponent(jButton2)
                .addGap(46, 46, 46)
                .addComponent(jButton3)
                .addContainerGap(73, Short.MAX_VALUE))
        );

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

    private void jButton1MousePressed(java.awt.event.MouseEvent evt) {                                      
        // TODO add your handling code here:
    }                                     

    private void jButton2MousePressed(java.awt.event.MouseEvent evt) {                                      
        // TODO add your handling code here:
    }                                     

    private void jButton3MousePressed(java.awt.event.MouseEvent evt) {                                      
        // TODO add your handling code here:
    }                                     

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

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    // End of variables declaration                   
}

The initcomponents() method initializes all of the Java swing components objects that your Front-End GUI uses, using the NetBeans GUI Builder. I see you are already using NetBeans GUI Builder and the IDE generated the code while you are designing,

@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    jButton1 = new javax.swing.JButton();
    jButton2 = new javax.swing.JButton();
    jButton3 = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jButton1.setText("jButton1");
    jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mousePressed(java.awt.event.MouseEvent evt) {
            jButton1MousePressed(evt);
        }
    });

    jButton2.setText("jButton1");
    jButton2.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mousePressed(java.awt.event.MouseEvent evt) {
            jButton2MousePressed(evt);
        }
    });

    jButton3.setText("jButton1");
    jButton3.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mousePressed(java.awt.event.MouseEvent evt) {
            jButton3MousePressed(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()
            .addGap(138, 138, 138)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jButton1)
                .addComponent(jButton2)
                .addComponent(jButton3))
            .addContainerGap(189, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(75, 75, 75)
            .addComponent(jButton1)
            .addGap(42, 42, 42)
            .addComponent(jButton2)
            .addGap(46, 46, 46)
            .addComponent(jButton3)
            .addContainerGap(73, Short.MAX_VALUE))
    );

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

So that is how the NetBeans IDE helping you to develop applications without typing more codes but with designing. Pretty easy huh:)

These swing components are automatically generated inside the above method whenever you make changes to the design of your GUI using the GUI builder.

You should not change any aspect of the above code within this method as this method is inextricably linked to the Front-End NetBeans GUI builder. If you change the code your Front-End also will be changed. But if you wish to change the code that is up to you to take care of it.

The initComponents(); method is called inside the constructor by default by NetBeans. And it is by default private . Running this initComponents(); method inside the Constructor will display the Front-End as soon as the application starts.

public Sterge() {
    initComponents();
}

But you can call the initComponents(); method wherever you like (constructor or inside other methods). For Java, it is just like any other method.

When I come to your menu question, I don't see any JMenuBar and JMenuItems are used. If you need them you can read about how to use Menus from here . But I see there are 3 JButtons as you said there are three buttons in Menu. So I assume these are the 3 buttons that you are saying about.

Look at the following codes in your class.

private void jButton1MousePressed(java.awt.event.MouseEvent evt) {                                      
    // TODO add your handling code here:
}                                     

private void jButton2MousePressed(java.awt.event.MouseEvent evt) {                                      
    // TODO add your handling code here:
}                                     

private void jButton3MousePressed(java.awt.event.MouseEvent evt) {                                      
    // TODO add your handling code here:
}  

Suppose you need to print Hello World! in the console after you click the jButton1 . Here is the place where you write the code. Inside the following method.

private void jButton1MousePressed(java.awt.event.MouseEvent evt) {                                      
    System.out.println("Hello World!");
} 

Once you click the above button MouseEvent will be triggered and you will see the Hello World! text on the console. According to your details, there are 3 buttons for 3 functions (exit, rules, play). Writing the code is up to you. :)

private void jButton1MousePressed(java.awt.event.MouseEvent evt) {                                      
    // Code for exit the game writes here
}                                     

private void jButton2MousePressed(java.awt.event.MouseEvent evt) {                                      
    // Code for show rules writes here
}                                     

private void jButton3MousePressed(java.awt.event.MouseEvent evt) {                                      
    // Code for play the game writes here
}  

If you look more carefully at the NetBeans-generated code, you will see that inside initComponents(); method there is this code,

jButton3.addMouseListener(new java.awt.event.MouseAdapter() {
    public void mousePressed(java.awt.event.MouseEvent evt) {
        jButton3MousePressed(evt);
    }
 });

NetBeans use this structure to prevent edits on the standard code that could lead to incorrect event handling, allowing you at the same time to write the code you need to be executed when that event happens.

As you have used MouseListener I suggest don't use a MouseListener. A JButton is designed to be used with anActionListener .

public void jButton3ActionPerformed(ActionEvent e) {
     // Your code here
}

The generated code ActionListener by the NetBeans GUI Builder will be,

jButton3.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
        jButton3ActionPerformed(evt);
    }
});

So I will stop writing from here as I can't cover all the points within this. The following links provide a very good quick start guide to the essentials of NetBeans GUI builder.

Hope this helps you. Happy Coding!

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