Mike John
Mike John

Reputation: 818

Java Panel Not Displaying

public class Test extends JFrame
{
    private static final long serialVersionUID = 1L;

    public static void main(String [] args)
    {

        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
               MyPanel p = new MyPanel();
               p.setVisible(true);
            }

       });
   }
}

The Panel code is dictates how this MyPanel should look.

public class MyPanel extends JPanel 
{
private static final long serialVersionUID = 1L;
private JTextField txtUsername;

public MyPanel() 
{
    setLayout(null);

    JPanel panel = new JPanel();
    panel.setLayout(null);
    panel.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));
    panel.setBackground(SystemColor.control);
    panel.setBounds(0, 0, 500, 500);
    add(panel);

    ImageIcon icon= new ImageIcon("C:/Users/Admin/Desktop/testPic.jpg");
    JLabel wlabel = new JLabel(icon);
    wlabel.setBounds(20, 10, 400, 222);
    panel.add(wlabel);

    JPanel panel_1 = new JPanel();
    panel_1.setBounds(36, 244, 614, 159);
    panel.add(panel_1);
    panel_1.setLayout(null);

    JLabel lblUsername = new JLabel("Username:");
    lblUsername.setBounds(40, 40, 100, 20);
    panel_1.add(lblUsername);
    lblUsername.setFont(new Font("Tahoma", Font.PLAIN, 18));

    txtUsername = new JTextField();
    txtUsername.setBounds(179, 52, 195, 30);
    panel_1.add(txtUsername);
    txtUsername.setColumns(10);

    JButton btnSubmit = new JButton("SUBMIT");
    btnSubmit.setBounds(424, 65, 145, 44);
    panel_1.add(btnSubmit);
    btnSubmit.setFont(new Font("Tahoma", Font.PLAIN, 18));

    btnSubmit.addActionListener(new ActionListener() 
    {
        public void actionPerformed(ActionEvent arg0) 
        {
        }
    });
}
}

Why don't I see the actual panel? The code compiles and runs but I don't see anything on my screen.

Upvotes: 2

Views: 159

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

You've got to add your JPanel to your JFrame. It's the JFrame that is the top level window that displays the entire GUI. Without a top level window either created directly, as described above, or indirectly, such as when you create a JOptionPane, the JPanel will never be seen.

So, rather than this:

public void run()
{
   MyPanel p = new MyPanel();
   p.setVisible(true);
}

Do this:

public void run()
{
   Test test = new Test();
   test.setVisible(true);
}

And then create your MyPanel in the Test constructor, and add it to Test there via a call to add(...).

Next we'll talk about why null layouts and setBounds(...) is a very bad thing.

Key tutorial links:

Upvotes: 2

Related Questions