【问题标题】:BorderLayout - JPanel in JPanelBorderLayout - JPanel 中的 JPanel
【发布时间】:2016-07-19 15:26:13
【问题描述】:

我想创建两个嵌套在另一个面板中的JPanel 容器,但是为什么它没有显示如下代码?我的两个面板好像不在ABC面板上?

public class ABC extends JPanel
{ 

      Frame frame;
      public  ABC(Frame frame)
       {
           super();
           this.frame = frame;
           setLayout(new BorderLayout());
           JPanel one = new JPanel();
           JPanel two = new JPanel();
           add(one,BorderLayout.NORTH);
           add(two,BorderLayout.CENTER);
           one.setVisible( true );
           two.setVisible( true );
       }
       public class one extends JPanel {
                  public one() {
                      setLayout(new FlowLayout(FlowLayout.LEFT));
                      createA();
                      setVisible(true);
                  }
              }
       public class two extends JPanel {
                   public two() {   
                       setLayout(new FlowLayout(FlowLayout.LEFT));
                       createB();
                       setVisible(true);
                   }
               }
     private void createA(){
                add(ButtonA);
                add(ButtonAA);
                add(ButtonAAA);
               }
     private void createB(){
                   add(ButtonB);
               }
}

【问题讨论】:

  • JPanel two = new JPanel();。它只是一个空面板,不会显示任何内容。更改它的背景颜色,或添加一些组件。
  • JPanel one = new JPanel 中,您没有创建新 JPanel 的实例。您必须实际调用onetwo 的构造函数
  • 1) 使用逻辑一致的形式缩进代码行和块。缩进是为了让代码流更容易理解! 2) 为了尽快获得更好的帮助,请发布minimal reproducible exampleShort, Self Contained, Correct Example。 3) 不要无故混用 Swing 和 AWT 组件。在这种情况下,没有充分的理由。将Frame frame; 更改为JFrame frame; 并根据编译器的警告调整其他代码位。 4) 在这种情况下,没有充分的理由扩展JPanel。 ..
  • .. 5) 请对代码和代码 sn-ps、HTML/XML 等结构化文档或输入/输出使用代码格式。为此,请选择文本并单击消息发布/编辑表单顶部的{} 按钮。

标签: java swing layout-manager border-layout


【解决方案1】:

你以错误的方式使用它,你必须使用你自己的类(一,二)而不是 JPANEL:

JPanel one = new one();
JPanel two = new two();
add(one,BorderLayout.NORTH);
add(two,BorderLayout.CENTER);

顺便说一句,尝试将类的名称更改为 One, Two

【讨论】:

    【解决方案2】:

    尝试更改面板的prefererSize,因为当您将面板放在 NORTH 或除 CENTER 以外的任何其他位置时,它应该有一个大小 使用边框查看面板的边缘

    one.setBorder(BorderFactory.createLineBorder(Color.black));
    two.setBorder(BorderFactory.createLineBorder(Color.blue));
    one.setpreferredsize(new new dimension(width,height));
    add(one,BorderLayout.NORTH);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-06
      • 1970-01-01
      • 1970-01-01
      • 2011-02-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多