0

This makes no sense to me. I have a fully working login screen called from my main class, the problem is the JPanel used to hold text areas etc. will not show up until I click the edge of the window (To expand it)

Here is my code:

Main

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;

public class SchoolSystem
{

public static void main (String [] args)
{

     Login lg = new Login();

}
}

Login

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;

 public class Login extends JFrame implements ActionListener
 {


 JFrame frame;

 JButton SUBMIT;
 JPanel panel;
 JLabel label1,label2;
 public Menus m = new Menus();
 final JTextField  text1,text2;

  {
      frame = new JFrame("Welcome");
      frame.setSize(310,110);
      frame.setVisible(true);
      label1 = new JLabel();
      label1.setText("User ID:");
      text1 = new JTextField(15);

      label2 = new JLabel();
      label2.setText("Password:");
      text2 = new JPasswordField(15);

      SUBMIT=new JButton("LOGIN");

      panel=new JPanel(new GridLayout(3,1));
      panel.add(label1);
      panel.add(text1);
      panel.add(label2);
      panel.add(text2);
      panel.add(SUBMIT);
      add(panel,BorderLayout.CENTER);
      SUBMIT.addActionListener(this);
      text2.addActionListener(this);
      setTitle("Welcome");
      frame.add(panel);
  }


 public void actionPerformed(ActionEvent ae)
      {
          //Gets the text inside the User ID and Password Panels
          String value1=text1.getText();
          String value2=text2.getText();

          //Compare text to actual ID and password, Act accordingly
          //In this case show a Menu for the Head Teacher
          if ((value1.equals("Admin") && value2.equals("1234"))){
          m.adminMenu();
          frame.setVisible(false);
          }
          else{
          if (value1.equals("Teach") && value2.equals("0000")) {
          m.teacherMenu();
          frame.setVisible(false);
          }

          else{
          JOptionPane.showMessageDialog(this,"Incorrect login or password",
          "Error",JOptionPane.ERROR_MESSAGE);
          }
          }
      }

 }
zx81
  • 41,100
  • 9
  • 89
  • 105
Matthew Cassar
  • 223
  • 2
  • 5
  • 13

2 Answers2

3
  • frame.setVisible(true); must be last code line, after all JComponents are added to the JFrame

  • last code lines could be frame.pack(); and frame.setVisible(true);

  • use JDialog for this job instead of JFrame,

  • best of could be to use CardLayout (call JFrame.pack() after switching from logon panel to another panel(s))

mKorbel
  • 109,525
  • 20
  • 134
  • 319
0

As mentioned by others, frame.setVisible(true) should be the last line of code. However, if you want to leave the code as is, then you should call frame.revalidate() at the end of your GUI code, right before the closing brace of the initializer block.

M3579
  • 890
  • 2
  • 11
  • 22