用java编写满足下列要求的程序: (1)1个顶层容器并将其内容窗格布局管理器设置为BorderLayout。 (2)创建2个中间容器并把它们添加到顶层容器。 (3)每个中间容器包含3个按钮,使用流式FlowLayout布局管理器。 (4)单击按钮时,在控制台显示信息指明按钮被单击。
时间: 2024-03-26 21:35:51 浏览: 20
好的,以下是Java程序的代码:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ButtonTest implements ActionListener {
private JFrame frame;
private JPanel panel1, panel2;
private JButton button1, button2, button3, button4, button5, button6;
public ButtonTest() {
// 创建顶层容器并设置BorderLayout布局管理器
frame = new JFrame("Button Test");
frame.setLayout(new BorderLayout());
// 创建中间容器1并添加3个按钮
panel1 = new JPanel(new FlowLayout());
button1 = new JButton("Button 1");
button2 = new JButton("Button 2");
button3 = new JButton("Button 3");
button1.addActionListener(this);
button2.addActionListener(this);
button3.addActionListener(this);
panel1.add(button1);
panel1.add(button2);
panel1.add(button3);
// 创建中间容器2并添加3个按钮
panel2 = new JPanel(new FlowLayout());
button4 = new JButton("Button 4");
button5 = new JButton("Button 5");
button6 = new JButton("Button 6");
button4.addActionListener(this);
button5.addActionListener(this);
button6.addActionListener(this);
panel2.add(button4);
panel2.add(button5);
panel2.add(button6);
// 将中间容器1和中间容器2添加到顶层容器中
frame.add(panel1, BorderLayout.NORTH);
frame.add(panel2, BorderLayout.SOUTH);
// 设置顶层容器的大小、可见性和关闭方式
frame.setSize(300, 200);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
System.out.println("Button " + command + " is clicked.");
}
public static void main(String[] args) {
new ButtonTest();
}
}
```
在这个程序中,我们创建了一个顶层容器并将其内容窗格布局管理器设置为BorderLayout。然后,我们创建了2个中间容器,每个中间容器包含3个按钮,使用流式FlowLayout布局管理器。单击按钮时,程序会在控制台显示信息指明按钮被单击。我们通过实现ActionListener接口来响应按钮单击事件,并在actionPerformed()方法中打印出按钮被单击的信息。
你可以根据需要修改按钮的文本或者布局管理器来测试程序的效果。
希望这个例子可以帮助你理解如何创建和使用Swing组件。