Need support with JButton events

后端 未结 2 1535
Happy的楠姐
Happy的楠姐 2021-01-16 16:10

I\'ve recently had a question answered about how to open a login panel in my main method in another class. Because i have not yet had any lessons in Swing yet (only basic Ja

2条回答
  •  旧时难觅i
    2021-01-16 16:34

    But now i need it to dispose the Login frame and access another method in my main.java. How can i achieve this from inside a private method in the Login.java?

    Here you have a design problem. You cannot call any frame's method because your ActionListener has its scope limited to Login panel. How to solve this? Implementing an ActionListener that has visibility enough to dispose the frame.

    Note: try to avoid NetBeans GUI Builder (or any GUI builder). It's easy but you miss a lot of things than making it by your own hand. You can even write a cleaner code. But it's necessary learn about Layout Managers

    Example of Code: this example illustrates the fact that you can achieve the same with less than half of lines of code.

    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.WindowEvent;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    
    public class Demo {    
    
        private void initGUI(){        
    
            final JTextField textField = new JTextField(20);
            final JFrame frame = new JFrame("Login");
            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);        
    
            JButton button = new JButton("Accept");        
            button.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    if("user".equals(textField.getText())){
                        frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));
                        // or simply frame.dispose()
                    } else {
                        JOptionPane.showMessageDialog(null, "Wrong user! Keep trying.", "Login failed", JOptionPane.WARNING_MESSAGE);
                    }
                }
            });
    
            JPanel login = new JPanel(new FlowLayout());
            login.add(new JLabel("User"));
            login.add(textField);
            login.add(button);
    
            frame.getContentPane().add(login);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }    
    
        public static void main(String[] args) {        
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    new Demo().initGUI();
                }
            });
        }
    }
    

提交回复
热议问题