import javax.swing.*; import java.awt.Container; import java.awt.Toolkit; import java.awt.event.*; public class P257 implements ActionListener, WindowListener {/* 捕获按钮上的单击事件需要实现第1个接口,捕获框架上的事件需要实现第2个接口*/ public P257() { JFrame f = new JFrame("EventDemol"); Container contentPane = f.getContentPane (); JButton b = new JButton("请单击我"); b.addActionListener(this);//按钮注册 contentPane. add(b);//放置按钮 f.pack(); f. show (); f.addWindowListener(this);//框架注册 } public static void main(String args[]) { new P257();//创建框架 } public void actionPerformed(ActionEvent e) { Toolkit. getDefaultToolkit().beep();// 产生“叮”响声 } public void windowActivated (WindowEvent e) { } public void windowClosed(WindowEvent e) { } public void windowOpened (WindowEvent e) { } public void windowDeactivated (WindowEvent e) { } public void windowIconified(WindowEvent e) { } public void windowDeiconified(WindowEvent e) { } public void windowClosing(WindowEvent e) //单击框架上的关闭按钮事件 { System.exit(0); } },在以上代码显示的窗口下方加上:小明:
时间: 2024-03-13 20:47:12 浏览: 80
好的,可以在 `JFrame` 中添加一个 `JLabel` 显示“小明”,具体如下所示:
```java
import javax.swing.*;
import java.awt.*;
public class P257 implements ActionListener, WindowListener {
public P257() {
JFrame f = new JFrame("EventDemol");
Container contentPane = f.getContentPane();
JButton b = new JButton("请单击我");
b.addActionListener(this);
contentPane.add(b);
f.pack();
f.show();
f.addWindowListener(this);
// 添加一个标签到窗口下面
JLabel label = new JLabel("小明");
contentPane.add(label, BorderLayout.SOUTH);
}
public static void main(String args[]) {
new P257();
}
public void actionPerformed(ActionEvent e) {
Toolkit.getDefaultToolkit().beep();
}
public void windowActivated(WindowEvent e) {
}
public void windowClosed(WindowEvent e) {
}
public void windowOpened(WindowEvent e) {
}
public void windowDeactivated(WindowEvent e) {
}
public void windowIconified(WindowEvent e) {
}
public void windowDeiconified(WindowEvent e) {
}
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
```
这样就在窗口下方添加了一个显示“小明”的标签。
阅读全文