2012-04-12 32 views
10

Tôi cần làm cho chương trình này xóa văn bản khỏi trường văn bản khi con chuột nhấp vào trường văn bản đó. Tôi đã thử một vài điều, nhưng không ai trong số họ vẫn chưa làm việc cho tôi.Cách xóa JTextField khi nhấp chuột vào JTextField

Đây là mã trong toàn bộ:

public class TimerClassPanel extends JFrame implements MouseListener{ 

    public TimerClassPanel(){ 
     setTitle("Timer Class"); 
     setSize(WIDTH, HEIGHT); 

     timer = new Timer(DELAY, new TimerEventHandler()); 

     pane = getContentPane(); 
     pane.setLayout(null); 

     int r = (int)(9.0 * Math.random()) + 1; 
     String str2 = Integer.toString(r); 

     label = new JLabel(str2, SwingConstants.CENTER); 
     label.setSize(150,30); 
     label.setLocation(0,0); 

     textField = new JTextField(); 
     textField.setSize(150,30); 
     textField.setLocation(150,0); 

     startB = new JButton("Start"); 
     startbh = new StartButtonHandler(); 
     startB.addActionListener(startbh); 
     startB.setSize(100,30); 
     startB.setLocation(0,30); 

     stopB = new JButton("Stop"); 
     stopbh = new StopButtonHandler(); 
     stopB.addActionListener(stopbh); 
     stopB.setSize(100,30); 
     stopB.setLocation(100,30); 

     exitB = new JButton("Exit"); 
     ebHandler = new ExitButtonHandler(); 
     exitB.addActionListener(ebHandler); 
     exitB.setSize(100,30); 
     exitB.setLocation(200,30);  

     pane.add(label); 

     pane.add(textField); 
     pane.add(startB); 
     pane.add(stopB); 
     pane.add(exitB); 

     timer = new Timer(DELAY, new TimerEventHandler()); 

     setVisible(true); 
     setDefaultCloseOperation(EXIT_ON_CLOSE); 
    } 

    private class TimerEventHandler implements ActionListener{ 
     public void actionPerformed(ActionEvent e){ 
      int r = (int)(9.0 * Math.random()) + 1; 
      String str = Integer.toString(r); 
      currentNum = ""; 
      currentNum = str; 
      label.setText(str); 
      repaint(); 
     } 
    } 

    public class StartButtonHandler implements ActionListener{ 
     public void actionPerformed(ActionEvent e){ 
      timer.start(); 
     } 
    } 

    public class StopButtonHandler implements ActionListener{ 
     public void actionPerformed(ActionEvent e){ 
      timer.stop(); 
     } 
    } 

    private class ExitButtonHandler implements ActionListener{ 
     public void actionPerformed(ActionEvent e){ 
      System.exit(0); 
     } 
    } 

    public static void main(String[] args){ 
     TimerClassPanel timerPanel = new TimerClassPanel(); 
     JOptionPane.showMessageDialog(null, "Type your guess (int between 1-9)" + 
       " in the field then press 'ENTER'"); 
    } 

    @Override 
    public void mouseClicked(MouseEvent e) { 
     if(e.getX() > 150 && e.getX() < 300 && e.getY() > 0 && e.getY() < 30) 
     { 
      textField.setText(""); 
      repaint(); 
     } 
    } 

    @Override 
    public void mouseEntered(MouseEvent arg0) { 
     // TODO Auto-generated method stub 

    } 

    @Override 
    public void mouseExited(MouseEvent arg0) { 
     // TODO Auto-generated method stub 

    } 

    @Override 
    public void mousePressed(MouseEvent arg0) { 
     // TODO Auto-generated method stub 

    } 

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

    } 
} 
+1

* "Đây là toàn bộ mã:" Lớp 'toàn bộ' sẽ cần nhập.Để được trợ giúp tốt hơn sớm hơn, hãy đăng một [SSCCE] (http://sscce.org/). –

Trả lời

23

TL; DR

Dù sao, việc đăng ký một MouseAdapter và trọng mouseClicked làm việc cho tôi,

import java.awt.FlowLayout; 
import java.awt.event.MouseAdapter; 
import java.awt.event.MouseEvent; 
import javax.swing.JFrame; 
import javax.swing.JTextField; 
import javax.swing.SwingUtilities; 

public class ClickAndClearDemo { 
    private static void createAndShowGUI(){ 
     JFrame frame = new JFrame(); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setLayout(new FlowLayout(FlowLayout.CENTER, 20, 20)); 

     final JTextField textField = new JTextField("Enter text here..."); 
     textField.addMouseListener(new MouseAdapter(){ 
      @Override 
      public void mouseClicked(MouseEvent e){ 
       textField.setText(""); 
      } 
     }); 

     frame.add(textField); 
     frame.pack(); 
     frame.setVisible(true); 
    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable(){ 
      @Override 
      public void run() { 
       createAndShowGUI(); 
      } 
     }); 
    } 
} 

Tôi hy vọng ví dụ này được bạn bắt đầu đi đúng hướng!

+0

Cảm ơn! Điều đó làm việc tuyệt vời cho tôi !! –

+0

@JimHalpert, Xin chào, Jim. – user1329572

+0

@JimHalpert, Nếu câu trả lời này hữu ích, vui lòng [chấp nhận] (http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) – user1329572

3

Điều này phù hợp với tôi. Tất nhiên, văn bản sẽ bị xóa khi bạn nhấp vào và bạn có thể nhập văn bản mới. Để xóa văn bản một lần nữa thông qua một lần nhấp, trường văn bản phải mất tiêu điểm và sau đó lấy lại tiêu điểm từ chuột. Tôi không hoàn toàn chắc chắn những gì bạn đang tìm kiếm ở đây.

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

import javax.swing.JFrame; 
import javax.swing.JTextField; 

public class ClickTextField extends JTextField implements MouseListener{ 

public static void main(String[] args) { 
    new ClickTextField(); 
} 

public ClickTextField() { 
    addMouseListener(this); 

    JFrame J = new JFrame(); 
    J.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    J.setSize(100,100); 
    J.getContentPane().add(this); 
    setText("Texty text..."); 
    J.show(); 
} 

@Override 
public void mouseClicked(MouseEvent e) { 

    setText(""); 

} 

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

} 

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

} 

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

} 

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

} 

} 
+0

phân lớp phụ là không tối ưu nếu bạn không không thêm chức năng thực sự mới (aka: không thể tiếp cận bằng cấu hình). Phơi bày api công cộng không được sử dụng công khai là .. một tội lỗi trong OO-world: _) – kleopatra

8

Bạn chỉ cần thêm FocusListener vào trường văn bản.

final JTextField textField = new JTextField("Enter text here..."); 
    textField.addFocusListener(new FocusListener(){ 
     @Override 
     public void focusGained(FocusEvent e){ 
      textField.setText(""); 
     } 
    }); 
2

Có phải xóa văn bản 'gợi ý' không?

Tôi nghĩ rằng đây là những gì bạn đang cố gắng làm ...

textField.addMouseListener(new MouseAdapter()) 
    { 
     public void mouseClicked(MouseEvent e) 
     { 
      if(textField.getText().equals("Default Text")) 
      { 
       textField.setText(""); 
       repaint(); 
       revalidate(); 
      }   
     } 
    }); 
0

tôi phải làm điều này là tốt. Những gì tôi đã làm chỉ đơn giản là thực hiện một tùy chỉnh JTextField. Một cái gì đó như:

import javax.swing.JMenuItem; 
import javax.swing.JPopupMenu; 
import javax.swing.JTextField; 

import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.awt.event.MouseEvent; 
import java.awt.event.MouseListener; 

@SuppressWarnings("serial") 
public class InputField extends JTextField implements MouseListener,ActionListener 
{ 
public InputField(String text) 
{ 
    super(text); 
    super.setHorizontalAlignment(RIGHT); 
    super.addMouseListener(this); 
} 

@Override 
public void mouseClicked(MouseEvent e) 
{ 
    // TODO Auto-generated method stub 
    if (getText().equals("0.0")) 
    { 
     setText(""); 
    } 
} 

@Override 
public void mouseEntered(MouseEvent e) 
{ 

} 

@Override 
public void mouseExited(MouseEvent e) 
{ 

} 

@Override 
public void mousePressed(MouseEvent e) { 
    maybeShowPopup(e); 
    // if the mouse is pressed and "0.0" is the text, we erase the text 
    if (getText().equals("0.0")) 
    { 
     setText(""); 
    } 
} 

@Override 
public void mouseReleased(MouseEvent e) 
{ 
    maybeShowPopup(e); 
} 

private void maybeShowPopup(MouseEvent event) 
{ 
    //if the user clicked the right mouse button 
    if (javax.swing.SwingUtilities.isRightMouseButton(event)) 
    { 
     //create (and show) the popup 
     createPopup().show(event.getComponent(), event.getX(), event.getY()); 
    } 
} 

private JPopupMenu createPopup() 
{ 
    JPopupMenu popupMenu = new JPopupMenu(); 
    //add the clearTextOption to the JPopupMenu 
    JMenuItem clearTextOption = new JMenuItem("Clear text"); 
    clearTextOption.addActionListener(this); 
    popupMenu.add(clearTextOption); 
    return popupMenu; 
} 

@Override 
public void actionPerformed(ActionEvent arg0) { 
    //clear the TextField 
    setText(""); 
} 

} //end custom TextField 

Trong TextField tùy chỉnh này, tôi chỉ đơn giản sử dụng MouseListener. Những lợi thế của việc một tùy chỉnh bao gồm:

  1. tôi có thể có nó trực tiếp thực hiện MouseListener (thay vì phải sử dụng một số nhầm lẫn vô danh lớp bên trong)
  2. tôi có thể làm một crapton của các tùy chỉnh (bao gồm các tùy chọn cho người dùng // nhấp chuột phải vào TextField và chọn một mục từ PopupMenu. // Tôi hiện đang làm việc trên các tùy chọn để người dùng sao chép, dán và kéo và thả.
  3. Tôi có thể thực hiện tất cả điều này mà không cần tập trung chính tệp .java với mã bổ sung mà sẽ làm cho nhiều thứ hơn để đào thông qua sau. Mặc dù MikeWarren.getAnswer(this) extends richard.getAnswer(this), tôi nghĩ rằng tôi sẽ xây dựng thêm một chút và hiển thị một số mã tôi thực sự được sử dụng trong một trong chương trình.
+0

1. là sai: không bao giờ phơi bày api không có nghĩa là để sử dụng công khai 2. cách cài đặt popup không có phân lớp là setComponentPopupMenu, Tất cả textComponents đã có hành động sao chép/dán/cắt có thể được sử dụng trong cửa sổ bật lên 3. có vẻ như bạn đang ghép nối quá nhiều điều: tách riêng dữ liệu khỏi chế độ xem sẽ làm sạch hầu hết các "crowding" - tóm tắt: không có lý do để phân lớp cho đến nay :-) – kleopatra

0

công khai JTextField userInput;

ngay sau khi thực thi văn bản:

userInput.setText (""); // rỗng

Điều này sẽ thực hiện.

0
jTextField2.addMouseListener(new MouseListener() { 
      @Override 
      public void mouseClicked(MouseEvent e) { 
       if (e.getButton()==1) { 
        jTextField2.setText(""); 
       }//3 = for right click 
       //2 for middlemouse 
      } 

      @Override 
      public void mousePressed(MouseEvent e) { 

      } 

      @Override 
      public void mouseReleased(MouseEvent e) { 

      } 

      @Override 
      public void mouseEntered(MouseEvent e) { 

      } 

      @Override 
      public void mouseExited(MouseEvent e) { 

      } 
     }); 

bạn cũng có thể thử với cách tiếp cận này.

Các vấn đề liên quan