我的Java代码在中间产生一个带有顶部和底部按钮的标签。我希望下面的代码产生如下所示的内容。
我只是不知道如何使用此代码f.add(b2,BorderLayout.CENTER);在中心添加2个标签。 。因为似乎只有一个项目可以在中间。我的代码希望两个标签都在中心对称。
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();
} }
键:嵌套JPanels,每个都使用自己的布局管理器。
创建一个JPanel并为其分配1行2列的new GridLayout(1, 2)
。将您的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, 2)); 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.setSize(400,500); f.setVisible(true); } public static void main(String[] args) throws IOException { new Nay2b(); } }
也:
pack()
。这将告诉布局管理器和组件根据其首选大小重新调整组件的大小。