Java : Swing : Hide frame after button pressed

后端 未结 4 638
闹比i
闹比i 2021-01-14 17:37

I have a button in a java frame that when pressed it reads a value from a text field and uses that string as a port name attempting to connect to a serial device.

If

4条回答
  •  耶瑟儿~
    2021-01-14 18:12

    Running your snippet (after removing/tweaking around the custom classes), throws an NPE. Reason is that the frame you'r accessing is null. And that's because it's never set. Better not rely on any field, let the button find its toplevel ancestor and hide that, like in

            public void actionPerformed(final ActionEvent e) {
    
                boolean success = true;
                if (success == false) {
                    System.out.println("Could not connect");
                    return;
                }
    
                Window frame = SwingUtilities.windowForComponent((Component) e
                        .getSource());
                frame.setVisible(false); //no problem :-)
    
            }
    

提交回复
热议问题