How can I dynamically add these elements to my JFrame?

时间:2017-07-10 15:19:33

标签: java swing jframe awt

I separated my GUI/JFrame from my Panel class so that I can keep the Swing components away from the rest of my code. However, I have a button that I would like to update my Frame in real time before I run a method from my Main class, but I can't get it to work. It looks something like (pseudocode):

public class GUI extends JFrame
{
    public GUI()
    {
        //frame setup
        Login login = new Login(this);
        frame.add(login);
        while(login.shouldContinue){login.panel.revalidate()}
        //continue
    }
}

public class Login
{
   Jpanel panel;
   Main main;
   Frame frame;
   boolean shouldContinue;
   public Login(Frame frame)
   {
    this.frame = frame;
    this.panel= new JPanel();
    this.main = new Main();

    //other panel elements

    JButton btn1 = new JButton ("Login");
    btn1.addActionListener(new ActionListener() { 
          public void actionPerformed(ActionEvent arg0){
                JLabel label = new JLabel("Logging in");
                panel.add(label);
                frame.add(panel);

                main.login();

                panel.remove(label1);
                JLabel label2 = new JLabel("Login Successful");
                panel.add(label2);
                frame.add(panel);
                this.shouldContinue=false;
          }
   }
}

The other elements of the panel display just fine, but when I click the button, nothing happens. How can I make the frame display the updated panel before running main.login()? I tried revalidating/repainting the panel but it didn't work.

1 个答案:

答案 0 :(得分:0)

You are describing the functionality provided by (J)Dialog.setModal(). But these days, an even easier way to do this is to just use JOptionPane

Login l = new Login();
res = JOptionPane.showConfirmDialog(null, login, "login", JOptionPane.OK_CANCEL_OPTION);
if (res == JOptionPane.OK_OPTION) {
  ...
}