2012-08-25 22 views
0

所以,這裏的情況:我有一個基本的JTextField在一個框架,並希望給用戶選擇,在文本框上單擊右鍵,然後,就像在Eclipse或Microsoft Word,給他在彈出菜單來複制他已經創造了文字或粘貼文本的選項。 如何使這個特殊的右擊事件的?特別右鍵單擊事件在Java中

這是該計劃的一個短版,我到目前爲止有:

import java.awt.*; 
import javax.swing.*; 

public class TestClass extends JFrame{ 

    private JFrame frame; 
    private JTextField textField; 

    /** 
    * Main method 
    * @param args 
    */ 
    public static void main(String[] args) { 
     EventQueue.invokeLater(new Runnable() { 
      public void run() { 
       try { 
        TestClass window = new TestClass(); 
        window.frame.setVisible(true); 
       } catch (Exception e) { 
        e.printStackTrace(); 
       } 
      } 
     }); 
    } 

    /** 
    * Create the window 
    */ 
    public TestClass() { 
     initialize(); 
    } 

    /** 
    * Initialize components (TextField) 
    */ 
    private void initialize() { 
     frame = new JFrame(); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setBounds(100, 100, 200, 100); 

     textField = new JTextField(); 
     textField.setText("TextField"); 
     textField.setFont(new Font("Arial", Font.PLAIN, 20)); 
     frame.add(textField); 
    } 
} 

回答

1

你應該用鼠標事件註冊一個事件你,那麼你必須使用一個彈出菜單將彈出當你點擊至今這裏是你的示例代碼!

  privatevoidformMouseClicked(java.awt.event.MouseEventevt){         

       if (evt.isPopupTrigger()){ 
        pop.show(evt.getComponent(),evt.getX(), evt.getY()); 
       } 

      }  
0
  private void textfiledMousePressed(java.awt. event.MouseEvent evt) { 

      if (evt.getModifiers() == MouseEvent.BUTTON3_MASK){ 

      p.show(evt.getComponent(), evt.getX(), evt.getY()); 

      } 

      } 

這也可以做了右鍵點擊