定义一个窗口frame和一个面板panel
定义两个按钮,分别显示姓名和账号,把按钮添加进panel,然后把panel添加到窗口
定义ActionListener或MouseListener事件,在点击按钮时调用JOptionPane的静态方法showMessageDialog,弹出当前按钮上的文字
把事件分别绑定到两个按钮上,实现按钮的点击效果
需要这个实验的代码
已经全部实现
感觉你的逻辑挺清晰的,看截图也实现了,你的需求是?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
class ButtonActionListener implements ActionListener {
private JButton jbObject;
public ButtonActionListener(JButton jbObject) {
this.jbObject = jbObject;
}
public void actionPerformed(ActionEvent aeObject) {
JOptionPane.showMessageDialog(jbObject.getParent(), jbObject.getText());
}
}
public class ComponentEvent extends JFrame {
public ComponentEvent(String strTitle) {
JPanel jpWindow = new JPanel();
JButton jbName = new JButton("姓名");
jbName.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent aeObject) {
JOptionPane.showMessageDialog(jpWindow, jbName.getText());
}
});
JButton jbAccount = new JButton("1234567890");
jbAccount.addActionListener(new ButtonActionListener(jbAccount));
jpWindow.setBackground(Color.white);
jpWindow.add(jbName);
jpWindow.add(jbAccount);
add(jpWindow);
setTitle(strTitle);
setBounds(320, 240, 320, 240);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
ComponentEvent ceWindow = new ComponentEvent("Java中的组件与事件处理");
}
}