首页 文章

如何在JFrame中添加外部JPanel?

提问于
浏览
0

enter image description here

我正在做大规模的计划 . 正如您所看到的,我有一个主要的JFrame和大约20个菜单项 . 每个菜单项都必须弹出一个新窗口 . 一开始我创建了一个JLayeredPanel,然后我将每个菜单项分配给JFrame里面的一个JPanel . 然后我将25个面板放在JLayeredPanel中...默认所有面板都设置为隐形,如:

panel1.setVisible(false);
panel2.setVisible(false);

等等

当用户单击一个菜单项时,其JPanel将可见,其余部分不可见 . 它看起来很乱,我有5000行代码 . 我使用了InternalFrame和TabbedPane,但我对它们并不满意 . 我想将我的代码拆分到不同的JPanel类中,并将它们分配给主JFrame . 我的意思是当用户点击每个菜单项时,它将调用外部JPanel并在主JFrame上的JPanel上呈现它 . 我在netbeans中使用设计模式,它为我做了一切,但简单的结构是这样的,它不起作用:

public class NewJPanel extends JPanel{
    //I have added buttons and etc on this panel
    ......

    }

public class  frame extends JFrame(){

        JPanel panel = new JPanel();
        .....
        Public frame(){
             frame.add(panel);
        }
        ......
        //When use click on the any button on the panel
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
            //this is not working

            NewJPanel fi = new NewJPanel ();
            panel1.add(fi);

            //or I tested this way separately but it did not work

           panel1.remove();
           panel1 = new NewJPanel();
           add(panel);
           invalidate();
        }       


}

请给我任何建议如何以专业的方式控制分裂课程中的这个程序 .

3 回答

  • 1
    • 从JFrame.getContentPane.remove(myPanel)中删除JPanel

    • 添加一个带常量的新JPanel,每次使用依赖于使用的LayoutManager及其在API中实现的方法

    • 调用JFrame . (重新)validate()和JFrame.repaint()作为最后的代码行,如果一切都完成,这些通知程序正确重绘可用区域

    • 再次使用CardLayout,没有重要的性能或内存问题

  • 0

    请给我任何建议如何以分裂的方式控制分裂课程中的这个程序 .

    好 .

    您应该将所有JPanel放在JTabbedPane中 . JTabbedPane将添加到JFrame中 .

    JFrame,JTabbedPane和每个JPanel将在一个单独的类中构建 .

    您使用Swing组件,而不是扩展它们 . 扩展Swing组件的唯一原因是,如果覆盖其中一个组件方法 .

    您还应该为每个JPanel创建模型类,以及为应用程序创建模型类 .

    阅读本文article,了解如何将Swing GUI放在一起 .

  • 1

    使代码更好

    public class NewJPanel extends JPanel{
    //I have added buttons and etc on this panel
    ......
    
    }
    
     public class  frame extends JFrame(){
    
        JPanel panel = new JPanel();
        .....
        Public frame(){
             //frame.add(panel); you dont need call frame because extends JFrame in frame class
             add(panel);
    
        ......
        //When use click on the any button on the panel
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
            //this is not working
    
            NewJPanel fi = new NewJPanel();
            add(fi);
    
            //or I tested this way separately but it did not work
    
           /*panel1.remove();
           panel1 = new NewJPanel();
           add(panel);
           invalidate();you must define panel1 before use it,like  :JPanel panel1 = new JPanel();*/
        }       
    
     }
    

相关问题