2.编写一个程序,实现如下功能: (1)编写类文件,创建一个窗体,采用边界布局方式,窗口命名为“MyJFrame”; (2)在窗体创建按钮对象和标签对象,分别位于窗体的北部和中部,分别显示为“提交”和“Welcome to our shop!” (3)为按钮添加事件监听器,当点击按钮时,标签显示“Welcome to come again!” (4)自定义窗口的大小和定位,并设置关闭窗口时退出程序功能。
时间: 2024-03-23 22:40:39 浏览: 22
以下是实现上述功能的Java程序代码:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MyJFrame extends JFrame implements ActionListener {
private JLabel label;
private JButton button;
public MyJFrame() {
super("MyJFrame");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 200);
setLocationRelativeTo(null);
setLayout(new BorderLayout());
label = new JLabel("Welcome to our shop!");
add(label, BorderLayout.CENTER);
button = new JButton("提交");
button.addActionListener(this);
add(button, BorderLayout.NORTH);
}
public void actionPerformed(ActionEvent e) {
label.setText("Welcome to come again!");
}
public static void main(String[] args) {
MyJFrame frame = new MyJFrame();
frame.setVisible(true);
}
}
```
这个程序创建了一个名为"MyJFrame"的窗口,采用边界布局方式。在窗口的中部显示了一个标签,内容为"Welcome to our shop!",在窗口的北部创建了一个按钮,显示为"提交"。当点击按钮时,标签内容会改变为"Welcome to come again!"。窗口的大小和位置可以自定义,关闭窗口时程序会退出。