Question

I am trying to add three panels on a single JFrame form. if i am only adding three panels they are being displayed but if i add the panel on split pane nothing is being displayed suggest the error in following code

 import javax.swing.*;
 import java.awt.*;
 class paneltest extends JFrame{
 paneltest()
 {
   Container cp=this.getContentPane();
   cp.setLayout(null);
   panel1 p1= new panel1();
   panel2 p2= new panel2();
   panel3 p3= new panel3();
   cp.add(p1);
   cp.add(p2);
   cp.add(p3);
   Dimension screenSize=Toolkit.getDefaultToolkit().getScreenSize();

   p1.setBounds(0,0,screenSize.width/3,screenSize.height);
   p2.setBounds(screenSize.width/3,0,screenSize.width/3,screenSize.height);
   p3.setBounds(2*(screenSize.width/3),0,screenSize.width/3,screenSize.height); 

   try{

       JSplitPane splitPaneLeft = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
       JSplitPane splitPaneRight = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
        splitPaneLeft.setLeftComponent( p1 );
        splitPaneLeft.setRightComponent( p2 );
        splitPaneRight.setLeftComponent( splitPaneLeft );
        splitPaneRight.setRightComponent( p3 );

        JPanel panelSplit = new JPanel();
        panelSplit.add(splitPaneRight);
        cp.add(panelSplit);
       panelSplit.setVisible(true);
       }
    catch(Exception ex)
    {

     JOptionPane.showMessageDialog(null,"exception occured"+ex);   

     }
   }
     public static void main(String arsg[])
    {

       paneltest frm= new paneltest();
       frm.show ();

       }

       }
       class panel1 extends JPanel
        {
        panel1()
           {
           setLayout(new FlowLayout());
           JLabel l1= new JLabel("panel1");
           add(l1);


           }    

           }

         class panel2 extends JPanel
        { 
         panel2()
           {
           setLayout(new FlowLayout());
           JLabel l1= new JLabel("panel2");
          add(l1);

           }    

         }
      class panel3 extends JPanel
       {
       panel3()
        {
          setLayout(new FlowLayout());
          JLabel l1= new JLabel("panel3");
          add(l1);


         }    

        }
Was it helpful?

Solution

Remove the line cp.setLayout(null). This will fix the initial problem.

After that:

  • indent the code
  • respect Java naming conventions
  • don't add panels to the content pane if you add them to the splitpanes right after. A component can be added to a single parent. It doesn't make sense to add them to both
  • don't use setBounds(). That's the role of the layout manager
  • don't extend JPanel and JFrame. Use them
  • Respect Swing's threading policy.
  • Don't catch (Exception)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top