简体   繁体   中英

Java Window Duplication Prevention

JButton btnNewButton = new JButton("Register Student");
btnNewButton.addMouseListener(new MouseAdapter() {
    @Override
    public void mouseClicked(MouseEvent arg0) {
        RegisterStudent panel_1 = new RegisterStudent();
        panel_1.setVisible(true);
    }
});
btnNewButton.setBounds(0, 162, 167, 37);
panel.add(btnNewButton);

Is there a way, that IF one specific window is open already, it cant be opened once again? Because, i don't want the user to click on a button several times, causing several windows to be opened with the same content?

Create the panel_1 variable outside of the mouse listener block and initialize it to null. When the mouse is clicked, check if panel_1 is null, and if it is, create it.

final RegisterStudent panel_1 = new RegisterStudent();
JButton btnNewButton = new JButton("Register Student");
btnNewButton.addMouseListener(new MouseAdapter() {
    @Override
    public void mouseClicked(MouseEvent arg0) {
        panel_1.setVisible(true);
    }
});
btnNewButton.setBounds(0, 162, 167, 37);
panel.add(btnNewButton);

You can get an array of all open windows from Window.getWindows() since 1.6 or all open Frames with Frame.getFrames() since 1.2. You can use the name property or the window class (RegisterStudent) to test if the windows is already open and set the focus on it instead open another one.

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