java在Frame中加入两个按钮(Button)和一个标签(Label),单击两个按钮,显示按钮的标签于Label。
时间: 2024-02-03 22:02:48 浏览: 27
可以使用如下代码实现:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyFrame extends JFrame implements ActionListener {
private JButton button1, button2;
private JLabel label;
public MyFrame() {
super("My Frame");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 300);
// 创建按钮和标签
button1 = new JButton("Button 1");
button2 = new JButton("Button 2");
label = new JLabel("Label");
// 将按钮和标签添加到窗口中
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
contentPane.add(button1);
contentPane.add(button2);
contentPane.add(label);
// 注册按钮的事件监听器
button1.addActionListener(this);
button2.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
// 根据事件源获取按钮的标签
String buttonText = ((JButton)e.getSource()).getText();
// 将按钮的标签显示在标签中
label.setText(buttonText);
}
public static void main(String[] args) {
MyFrame frame = new MyFrame();
frame.setVisible(true);
}
}
```
在上面的代码中,我们创建了一个继承自 `JFrame` 的 `MyFrame` 类,并实现了 `ActionListener` 接口。在 `MyFrame` 类的构造函数中,我们创建了两个按钮和一个标签,并将它们添加到窗口中。同时,我们还注册了按钮的事件监听器,当按钮被单击时,会触发 `actionPerformed` 方法,在该方法中,我们根据事件源获取按钮的标签,并将它显示在标签中。最后,在 `main` 方法中,我们创建了一个 `MyFrame` 对象,并将其设置为可见。