在java中的分割窗格上添加jpanel

时间:2012-12-25 08:54:58

标签: java swing jpanel jsplitpane

我正在尝试在单个JFrame表单上添加三个面板。如果我只添加三个面板,他们正在显示,但如果我在拆分窗格上添加面板,则不会显示任何内容 建议以下代码中的错误

 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);


         }    

        }

1 个答案:

答案 0 :(得分:2)

删除第cp.setLayout(null)行。这将解决最初的问题。

之后:

  • 缩进代码
  • 尊重Java命名约定
  • 如果您将面板添加到内容窗格后,请不要将其添加到内容窗格。可以将组件添加到单个父组件。将它们添加到两个
  • 是没有意义的
  • 请勿使用setBounds()。这是布局管理员的角色
  • 不要扩展JPanel和JFrame。使用它们
  • 尊重Swing's threading policy
  • 不要catch (Exception)