将 2 个标签放入 jframe 边框布局的中间

put 2 labels into the middle of a jframe border layout

我的 java 代码在中间生成一个标签,顶部和底部都有一个按钮。我希望下面的代码产生如下所示的内容。

我只是不知道如何使用这段代码向中心添加 2 个标签 f.add(b2,BorderLayout.CENTER); .因为似乎只有一个项目可以在中心。我的代码希望两个标签在中心是对称的。

import java.awt.*;
import java.io.IOException;
import javax.swing.*;

public class may2 {
    Frame f;  
    JLabel b2=new JLabel("");;  

    may2() throws IOException{ 
        f=new JFrame();  
        JButton b1 = new JButton("First");
        JButton b3 = new JButton("Second");
        f.add(b1,BorderLayout.NORTH); 
        f.add(b2,BorderLayout.CENTER);  
        f.add(b3,BorderLayout.SOUTH); 
        f.setSize(400,500);  
        f.setVisible(true);  
    }

    public static void main(String[] args) throws IOException {  
        new may2();  
    }  

}

关键:嵌套 JPanel,每个都使用自己的布局管理器。

创建一个 JPanel 并为其指定 new GridLayout(1, 0) 1 行,列数可变。将 JLabel 添加到此 JPanel,然后将此 JPanel 添加到主容器的 BorderLayout.CENTER 位置,即使用 BorderLayout 的容器。

例如,

import java.awt.*;
import java.io.IOException;
import javax.swing.*;

public class May2b {
    Frame f;  
    JLabel label1 = new JLabel("Label 1");  
    JLabel label2 = new JLabel("Label 2");  

    May2b() throws IOException{ 
        JPanel centerPanel = new JPanel(new GridLayout(1, 0));
        centerPanel.add(label1);
        centerPanel.add(label2);

        f = new JFrame();  
        JButton b1 = new JButton("First");
        JButton b3 = new JButton("Second");
        f.add(b1,BorderLayout.NORTH); 
        f.add(centerPanel, BorderLayout.CENTER);  
        f.add(b3,BorderLayout.SOUTH); 

        f.pack();
        // f.setSize(400,500);  

        f.setVisible(true);  
    }

    public static void main(String[] args) throws IOException {  
        new May2b();  
    }  
}

另外:

  • Class 名称应以大写字母开头,以遵循 Java 约定。这将使其他人更容易阅读您的代码。
  • 避免设置 JPanel 的大小,而是在添加所有组件之后并在将其设置为可见之前对其调用 pack()。这将告诉布局管理器和组件根据它们的首选大小调整组件的大小。