java 动态添加 JPanel 到 Jframe

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5302622/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 10:30:22  来源:igfitidea点击:

Adding JPanel to Jframe dynamically

javaswingjpanel

提问by Vade

I have a form on my Java application which basically is to provide the user with a list of data from a DB query. one idea was to use a table and populate each row with data from my resultset. However when designing the UI my team and i decided that it didnt look as smooth as we wanted. So we thought we would look into creating a custom view of the results in a panel. we wanted it to look something like: Desired custom view

我的 Java 应用程序中有一个表单,它基本上是为用户提供来自数据库查询的数据列表。一个想法是使用一个表格并用我的结果集中的数据填充每一行。然而,在设计 UI 时,我和我的团队认为它看起来并不像我们想要的那样流畅。所以我们认为我们会考虑在面板中创建一个自定义的结果视图。我们希望它看起来像: 所需的自定义视图

So instead of rows of a table it will look like this with one for each enquiry on the resultset.

因此,代替表的行,它看起来像这样,结果集上的每个查询都有一个。

The problem i am having is coding this. I spent a good deal of time trying to workout how to add a component to a JForm. as netbeans seem to by default set up the ui as a grouplayout? so I worked out how to add 1 panel using:

我遇到的问题是对此进行编码。我花了很多时间尝试练习如何将组件添加到 JForm。因为 netbeans 似乎默认将 ui 设置为 grouplayout?所以我想出了如何使用以下方法添加 1 个面板:

javax.swing.JLabel idLbl;
 javax.swing.JLabel jLabel1;
 javax.swing.JLabel jLabel3;
 javax.swing.JLabel jLabel5;
 javax.swing.JLabel jLabel7;
 javax.swing.JPanel jPanel1;
 javax.swing.JLabel prefContactLbl;
 javax.swing.JLabel propertyLabel;
    jPanel1 = new javax.swing.JPanel();
    jLabel1 = new javax.swing.JLabel();
    idLbl = new javax.swing.JLabel();
    jLabel3 = new javax.swing.JLabel();
    propertyLabel = new javax.swing.JLabel();
    jLabel5 = new javax.swing.JLabel();
    contactLabel = new javax.swing.JLabel();
    jLabel7 = new javax.swing.JLabel();
    prefContactLbl = new javax.swing.JLabel();

    jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

    jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12));
    jLabel1.setText("Enquiry Id:");
    jLabel1.setName("jLabel"+i);

    idLbl.setText("jLabel2");

    jLabel3.setFont(new java.awt.Font("Tahoma", 1, 12));
    jLabel3.setText("Property:");

    propertyLabel.setText("A property Address in some town with a postcode");

    jLabel5.setFont(new java.awt.Font("Tahoma", 1, 12));
    jLabel5.setText("Contact:");

    contactLabel.setText("A Persons Name ( 01010100011)");

    jLabel7.setFont(new java.awt.Font("Tahoma", 1, 12));
    jLabel7.setText("Prefered Contact:");

    prefContactLbl.setText("Email/Phone");

    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addComponent(jLabel1)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(idLbl)
                    .addGap(18, 18, 18)
                    .addComponent(jLabel3)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(propertyLabel))
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addComponent(jLabel7)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(prefContactLbl)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(jLabel5)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(contactLabel)))
            .addContainerGap(20, Short.MAX_VALUE))
    );
    jPanel1Layout.setVerticalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel1)
                .addComponent(idLbl)
                .addComponent(jLabel3)
                .addComponent(propertyLabel))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel7)
                .addComponent(prefContactLbl)
                .addComponent(jLabel5)
                .addComponent(contactLabel))
            .addContainerGap())
    );

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
     getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(10 , 10, 10)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                 .addContainerGap(100, Short.MAX_VALUE))
    );

    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(570, Short.MAX_VALUE))
    );

The main problem I am faced is adding more than 1 dynamically I am completly unsure how to go about it as all i can find is to set the layout not update it. And I cant set how many .addcomponent as its dynamic. Really confused on how to go about this.

我面临的主要问题是动态添加超过 1 个我完全不确定如何去做,因为我能找到的只是设置布局而不是更新它。而且我不能设置多少 .addcomponent 作为它的动态。真的很困惑如何解决这个问题。

Sorry if its hard to work out what I am trying to get across easier to think of it but putting it into words is a nightmare.

对不起,如果很难弄清楚我想要表达的东西更容易想到它,但把它变成文字是一场噩梦。

回答by Matt Crinklaw-Vogt

Starting off by encapsulating things a bit more will make your life much easier. Make a subclass of JPanelthat represents the view for one enquiry entry: EnquiryPanel. The EnquiryPanelwould have code in it that nearly matches what you pasted above, except that it will fill itself in from the constructor parameters that you pass in and it will be a JPanelitself.

开始时多封装一些东西会让你的生活更轻松。JPanel为一个查询条目创建一个代表视图的子类:EnquiryPanel。该EnquiryPanel会对代码它几乎符合您在上面粘贴什么,只是将填补自己在从您在通过构造函数的参数,这将是一个JPanel本身。

public class EnquiryPanel extends JPanel {
   public EnquiryPanel(Result dbResult) {
     // your layout code from above, but this is the content pane and
    // the fields are populated from the dbResult object
   }
}

You can then dynamically add instances of EnquiryPanelto a container panel whose layout is a vertical BoxLayout. I call this container panel ResultsPanelbelow.

然后,您可以将 的实例动态添加EnquiryPanel到布局为垂直 BoxLayout 的容器面板。我ResultsPanel在下面称这个容器面板。

public class ResultsPanel extends JPanel {
  public ResultsPanel() {
    // Layout our contents vertically
    BoxLayout layout = new BoxLayout(this, BoxLayout.Y_AXIS);
    this.setLayout(layout);
  }
  // method to iterate over the results from the database
  // construct an EnquiryPanel and add that EnquiryPanel to ourselves
  public void layoutEnquiryResults(ResultCollection results) {
     for (Result result : results) {
        EnquiryPanel eqPanel = new EnquiryPanel(result);
        add(eqPanel);
     }
     revalidate();
  }
}

Finally you would add an instance of ResultsPanelto your JFrame.

最后,您将向ResultsPanel您的JFrame.

ResultsPanel resultsPanel = new ResultsPanel();
resultsPanel.layoutEnquiryResults(myResultSet);
getContentPane().add(resultsPanel);

回答by camickr

Don't use GroupLayout. The constraints are generally too confusing to set by hand.

不要使用 GroupLayout。约束通常太混乱而无法手动设置。

Instead I would probably use a vertical BoxLayout. After you add each panel don't forget to revalidate() the parent panel.

相反,我可能会使用垂直的 BoxLayout。添加每个面板后,不要忘记 revalidate() 父面板。