2 java swing jlabel layout-manager 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();
}
}
Run Code Online (Sandbox Code Playgroud)
关键:嵌套 JPanel,每个都使用自己的布局管理器。
创建一个 JPanel 并给它一个new GridLayout(1, 0)for 1 row,可变列数。将您的 JLabels 添加到此 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();
}
}
Run Code Online (Sandbox Code Playgroud)
还:
pack()在添加所有组件之后和将其设置为可见之前调用它。这将告诉布局管理器和组件根据其首选大小重新调整组件的大小。| 归档时间: |
|
| 查看次数: |
175 次 |
| 最近记录: |