java中取得点击那个按钮的文字

2024-12-02 16:53:41
推荐回答(3个)
回答(1):

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.*;

public class sdsad extends JFrame {
static JButton item,item2;
public sdsad (){
this.setLayout(new FlowLayout());
item= new JButton("一");
this.add(item);
item.addMouseListener( new clickAction());
item2= new JButton("二");
this.add(item2);
item2.addMouseListener(new clickAction());
this.setVisible(true);
this.setBounds(30, 30, 300, 300);
}
public static void main(String a[]){
new sdsad();
}
}
class clickAction implements MouseListener{
public void mouseClicked(MouseEvent e){
System.out.println("你点击的按迹让缓钮姿模滑誉上的文字是"+((JButton) (e.getSource())).getText() );
((JButton)e.getSource()).setBackground(Color.blue);
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
}

回答(2):

private TextArea ta=new TextArea(6,50);
Button1.addActionListener(new FirstListener());
class FirstListener implements ActionListener{
public void actionPerformed(ActionEvent e){
ta.append("nin dan ji le:"+e.getActionCommand()+"\n");
}
}
也可用匿名李让瞎哪空内部滑磨类

回答(3):

按钮一般都是直接addactionlistener的。很少有你响应mouselistener的吧