有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java是否可以删除两个单独文本字段中的文本,具体取决于使用一个鼠标侦听器单击哪个字段?

我有两个jTextField,其中包含文本和一个鼠标侦听器:

JTextField tf1 = new JTextField("Input your text here: ");
JTextField tf2 = new JTextField("Input your pattern here: ");
tf1.addMouseListener(mm);
tf2.addMouseListener(mm);

我想删除使用MouseStener单击的文本字段中的文本:

MouseListener mm = new MouseAdapter(){
        public void mouseClicked(MouseEvent e){
            tf1.setText("");
            //tf2.setText("");
        }
    };

然而,我只能设法擦除两个或一个。我可以再添加一个MouseStener,但我很好奇是否有可能创建这样的MouseStener,根据我单击的文本字段擦除文本


共 (1) 个答案

  1. # 1 楼答案

    尝试此操作,它将基于鼠标单击文本字段进行擦除

    import javax.swing.*;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.event.*;
    public class JFrameTest{
    
    public static void main(String[] args){
    
        JFrame frame= new JFrame(); 
        frame.setTitle("JFrame");
    
        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
    
        JPanel panel = new JPanel(new GridBagLayout());
        GridBagConstraints constr = new GridBagConstraints();
    
        constr.gridx=0;
        constr.gridy=0;
    
        JTextField txt1 = new JTextField(20);
        txt1.setText("abc");
        JTextField txt2= new JTextField(20);
        txt2.setText("efg"); 
    
        constr.gridx=1;
        panel.add(txt1, constr);
        constr.gridy=1;
        panel.add(txt2, constr);
    
        MouseListener mm = new MouseAdapter(){
            public void mouseClicked(MouseEvent e){
               //System.out.println(e);
               //System.out.println(e.getSource());
    
               //be sure to have the component in case that listener is added on more objs
               if(e.getSource() instanceof JTextField)
               {
                   //set whatever you wanted on each TF individualy
                   ((JTextField)e.getSource()).setText("");
               }
            }
        };
        //add the same listener on both but process on each as click
        txt1.addMouseListener(mm);
        txt2.addMouseListener(mm);
    
        mainPanel.add(panel);
    
        frame.add(mainPanel);
        frame.pack();
        frame.setSize(400, 400);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
    }