1 54 55 package com.mullassery.act.gui.components; 56 57 import java.awt.Dimension ; 58 import java.awt.Toolkit ; 59 import java.awt.datatransfer.DataFlavor ; 60 import java.awt.datatransfer.Transferable ; 61 import java.awt.event.ActionEvent ; 62 import java.awt.event.MouseAdapter ; 63 import java.awt.event.MouseEvent ; 64 65 import javax.swing.AbstractAction ; 66 import javax.swing.JMenuItem ; 67 import javax.swing.JPopupMenu ; 68 import javax.swing.JTextField ; 69 70 import com.mullassery.act.gui.TextData; 71 72 77 public class TTextField extends JTextField implements TextData{ 78 private JPopupMenu popup; 79 80 public TTextField() { 81 this(null); 82 } 83 84 85 public TTextField(String val) { 86 this(val, 200, 20); 87 } 88 89 90 public TTextField(String val, int w) { 91 this(val, w, 20); 92 } 93 94 95 public TTextField(String val, int w, int h) { 96 super(val); 97 setPreferredSize(new Dimension (w, h)); 98 addMouseListener(new MouseAdapter () { 99 public void mousePressed(MouseEvent e) { 100 showPopup(e); 101 } 102 public void mouseReleased(MouseEvent e) { 103 showPopup(e); 104 } 105 }); 106 } 107 108 private void showPopup(MouseEvent e) { 109 if (e.isPopupTrigger()) { 110 if (popup == null) { 111 popup = new JPopupMenu (); 112 popup.add(new TextEditAction("cut")); 113 popup.add(new TextEditAction("copy")); 114 popup.add(new TextEditAction("paste")); 115 } 116 JMenuItem cut = (JMenuItem )popup.getComponent(0); 117 JMenuItem copy = (JMenuItem )popup.getComponent(1); 118 String str = getSelectedText(); 119 if (str != null && str.length() > 0) { 120 cut.setEnabled(true); 121 copy.setEnabled(true); 122 } else { 123 cut.setEnabled(false); 124 copy.setEnabled(false); 125 } 126 JMenuItem paste = (JMenuItem )popup.getComponent(2); 127 Transferable content = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(this); 128 if (content.isDataFlavorSupported(DataFlavor.stringFlavor)) { 129 paste.setEnabled(true); 130 } else { 131 paste.setEnabled(false); 132 } 133 popup.show(this, e.getX(), e.getY()); 134 } 135 } 136 137 private class TextEditAction extends AbstractAction { 138 String name; 139 TextEditAction(String name) { 140 super(name); 141 this.name = name; 142 } 143 144 public void actionPerformed(ActionEvent e) { 145 if (this.name.equals("cut")) { 146 cut(); 147 } else if (this.name.equals("copy")) { 148 copy(); 149 } else if (this.name.equals("paste")) { 150 paste(); 151 } 152 } 153 } 154 } | Popular Tags |