JTextField有文字,当鼠标点击时返回监JTextField中的内容,监听怎么设?最好有源代码

时间紧急,请尽快,拜托
2024-12-31 11:20:30
推荐回答(2个)
回答1:

实现MouseListener鼠标监听即可
你可能是实现ActionListener事件监听,文本框中当回车时才会触发事件,才会调用actionPerformed方法

看看下面代码:
import java.awt.BorderLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class T extends JFrame implements MouseListener{
JTextField jtf = new JTextField(10);
public T(){
jtf.addMouseListener(this);
add(jtf,BorderLayout.NORTH);
setSize(300,300);
setLocation(300, 200);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String []args){
new T();
}

@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub

}

@Override
public void mouseEntered(MouseEvent e) {

}

@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent e) {
Object o=e.getSource();
String s=jtf.getText();
if(o.equals(jtf)&&!"".equals(s))
System.out.println(s);
}

@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub

}
}

回答2:

JTextField jtf = new JTextField();
jtf.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//这里就可以获取jtf中的内容了
String str = jtf.getText().trim();
}
});