简体   繁体   中英

Open new panel with button clicked

Java Swing GUI:

I am using ActionListener to preform the action when a button is clicked. What i want to do is when a button is clicked, open a new panel, but load/get the new panel from a different file.

This is what i have so far but i rather just link to another file. THANKS! =]

   public void actionPerformed(java.awt.event.ActionEvent e) {
                    //something like this...
                    loadFile(newPlane.java);
}

Update:

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


        private void inventoryDisplayActionPerformed(java.awt.event.ActionEvent evt) {
        //open a new panel by opening a new file ex: inventory.java  
        }

the reason im asking this is because when im creating a GUI program with netbeans... i have no idea how to make a new planel with the "design view" when the button is clinked. Since netbeans only displays the main panel.

Java does not work on the basis of includes, so you need to define classes, and instantiate them.

you could make a static factory method to get a fully configured JPanel:

public class ClassWhereStored {
    public static JPanel newJPanel(){
        JPanel panel = new JPanel();
        // configure it
        return panel;
    }
}

...

public void actionPerformed(java.awt.event.ActionEvent e) {
    JPanel panel = ClassWhereStored.newPanel()
    frame.add(panel);          
}

What you'll need to do, for you code, is to put the class file in the same folder.

ie, in relation to the following code...

public void actionPerformed(java.awt.event.ActionEvent e) {
    //something like this...
    loadFile(newPlane.java);
}

...you need to compile newPlane.java, take the class file that is created and place it in the same folder as your class that's trying to "loadfile".

Then, in your class (I'm assuming it extends JFrame or JPanel), you need to do this, instead of loadFile:

public void actionPerformed(java.awt.event.ActionEvent e) {
    newPlane plane = new newPlane();
    add(plane);
}

Usually, it's just easier to write the class code in the same place. Don't forget that you might have to remove components from your class.

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