import java.awt.BorderLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class FrameTest extends JFrame {
private JTextField tf1, tf2;
public FrameTest() {
super("测试");
tf1 = new JTextField("姓");
tf2 = new JTextField("名");
tf1.addMouseListener(new MouseListener() {
public void mouseReleased(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
if (tf1.getText().trim().equals("")) {
tf1.setText("姓");
}
}
public void mouseEntered(MouseEvent e) {
if (tf1.getText().trim().equals("姓")) {
tf1.setText(null);
}
}
public void mouseClicked(MouseEvent e) {
}
});
tf2.addMouseListener(new MouseListener() {
public void mouseReleased(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
if (tf2.getText().trim().equals("")) {
tf2.setText("名");
}
}
public void mouseEntered(MouseEvent e) {
if (tf2.getText().trim().equals("名")) {
tf2.setText(null);
}
}
public void mouseClicked(MouseEvent e) {
}
});
this.add(tf1, BorderLayout.NORTH);
this.add(tf2, BorderLayout.SOUTH);
this.setSize(300, 200);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public static void main(String[] args) {
new FrameTest();
}
}
你参考一下,还不会就回复我
追问mousePressed(); mouseReleased();mouseClicked();mouseEntered();mouseExited(); 是不是总要一起用?比如你上面tf1鼠标事件中只有mouseEntered();mouseExited()有代码,其他mousePressed(); mouseReleased();mouseClicked()都是空方法.
追答不是总要的,因为我在那里用的是接口,接口就一定要实现里面的抽象方法,你完全可以用自定义类,然后继承mouse适配器,再重写Enter和Exit方法,就不用出现Press等其他空方法
本回答被提问者和网友采纳