Java by API/javax.swing/JTextField
Содержание
- 1 JTextField: addActionListener(ActionListener s)
- 2 JTextField: addFocusListener(FocusListener l)
- 3 JTextField: addKeyListener(KeyListener l)
- 4 JTextField: copy()
- 5 JTextField: cut()
- 6 JTextField: getActions()
- 7 JTextField: getCaretPosition()
- 8 JTextField: getDocument()
- 9 JTextField: getHorizontalVisibility()
- 10 JTextField: getHorizontalVisibility() (2)
- 11 JTextField: getInputMap()
- 12 JTextField: getKeymap()
- 13 JTextField: getScrollOffset()
- 14 JTextField.LEADING
- 15 JTextField.LEFT
- 16 JTextField: modelToView(int pos)
- 17 JTextField: paste()
- 18 JTextField: read(Reader in, Object desc)
- 19 JTextField: registerKeyboardAction(ActionListener anAction,String aCommand,KeyStroke aKeyStroke,int aCondition)
- 20 JTextField: requestFocus()
- 21 JTextField: setDocument(Document doc)
- 22 JTextField: setFocusAccelerator(char aKey)
- 23 JTextField: setHorizontalAlignment(int alignment)
- 24 JTextField: setInputVerifier(InputVerifier input)
- 25 JTextField: setNavigationFilter(NavigationFilter filter)
- 26 JTextField: setPreferredSize(Dimension preferredSize)
- 27 JTextField: setTransferHandler(TransferHandler newHandler)
- 28 JTextField.TRAILING
- 29 JTextField: write(Writer out)
- 30 new JTextField(String text)
- 31 new JTextField(String text, int columns)
JTextField: addActionListener(ActionListener s)
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class MainClass extends JPanel implements ActionListener {
JTextField jtf = new JTextField(15);
public MainClass() {
add(jtf);
jtf.addActionListener(this);
}
// Show text when user presses ENTER.
public void actionPerformed(ActionEvent ae) {
System.out.println(jtf.getText());
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.getContentPane().add(new MainClass());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 200);
frame.setVisible(true);
}
}
JTextField: addFocusListener(FocusListener l)
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Main {
public static void main(String[] a) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextField textField = new JTextField("A TextField");
textField.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {
displayMessage("Focus gained", e);
}
public void focusLost(FocusEvent e) {
displayMessage("Focus lost", e);
}
void displayMessage(String prefix, FocusEvent e) {
System.out.println(prefix
+ (e.isTemporary() ? " (temporary):" : ":")
+ e.getComponent().getClass().getName()
+ "; Opposite component: "
+ (e.getOppositeComponent() != null ? e.getOppositeComponent().getClass().getName()
: "null"));
}
});
frame.add(textField,"North");
frame.add(new JTextField(),"South");
frame.setSize(300, 200);
frame.setVisible(true);
}
}
JTextField: addKeyListener(KeyListener l)
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.InputVerifier;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;
public class MainClass {
public static void main(String args[]) throws Exception {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextField nameTextField = new JTextField();
frame.add(nameTextField, BorderLayout.NORTH);
KeyListener keyListener = new KeyListener() {
public void keyPressed(KeyEvent keyEvent) {
printIt("Pressed", keyEvent);
}
public void keyReleased(KeyEvent keyEvent) {
printIt("Released", keyEvent);
}
public void keyTyped(KeyEvent keyEvent) {
printIt("Typed", keyEvent);
}
private void printIt(String title, KeyEvent keyEvent) {
int keyCode = keyEvent.getKeyCode();
String keyText = KeyEvent.getKeyText(keyCode);
System.out.println(title + " : " + keyText + " / " + keyEvent.getKeyChar());
}
};
nameTextField.addKeyListener(keyListener);
frame.setSize(250, 100);
frame.setVisible(true);
}
}
JTextField: copy()
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
public class Main {
JTextField jtf = new JTextField(15);
JButton jbtnCut = new JButton("Cut");
JButton jbtnPaste = new JButton("Paste");
JButton jbtnCopy = new JButton("Copy");
public Main() {
JFrame jfrm = new JFrame("Cut, Copy, and Paste");
jfrm.setLayout(new FlowLayout());
jfrm.setSize(230, 150);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jbtnCut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent le) {
jtf.cut();
update();
}
});
jbtnPaste.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent le) {
jtf.paste();
update();
}
});
jbtnCopy.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent le) {
jtf.copy();
update();
}
});
jtf.addCaretListener(new CaretListener() {
public void caretUpdate(CaretEvent ce) {
update();
}
});
jfrm.add(jtf);
jfrm.add(jbtnCut);
jfrm.add(jbtnPaste);
jfrm.add(jbtnCopy);
jfrm.setVisible(true);
}
private void update() {
System.out.println("All text: " + jtf.getText());
if (jtf.getSelectedText() != null)
System.out.println("Selected text: " + jtf.getSelectedText());
else
System.out.println("Selected text: ");
}
public static void main(String args[]) {
new Main();
}
}
JTextField: cut()
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
public class Main {
JTextField jtf = new JTextField(15);
JButton jbtnCut = new JButton("Cut");
JButton jbtnPaste = new JButton("Paste");
JButton jbtnCopy = new JButton("Copy");
public Main() {
JFrame jfrm = new JFrame("Cut, Copy, and Paste");
jfrm.setLayout(new FlowLayout());
jfrm.setSize(230, 150);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jbtnCut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent le) {
jtf.cut();
update();
}
});
jbtnPaste.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent le) {
jtf.paste();
update();
}
});
jbtnCopy.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent le) {
jtf.copy();
update();
}
});
jtf.addCaretListener(new CaretListener() {
public void caretUpdate(CaretEvent ce) {
update();
}
});
jfrm.add(jtf);
jfrm.add(jbtnCut);
jfrm.add(jbtnPaste);
jfrm.add(jbtnCopy);
jfrm.setVisible(true);
}
private void update() {
System.out.println("All text: " + jtf.getText());
if (jtf.getSelectedText() != null)
System.out.println("Selected text: " + jtf.getSelectedText());
else
System.out.println("Selected text: ");
}
public static void main(String args[]) {
new Main();
}
}
JTextField: getActions()
import java.awt.BorderLayout;
import java.util.Hashtable;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.text.DefaultEditorKit;
public class MainClass {
public static void main(String args[]) throws Exception {
JFrame frame = new JFrame("Cut/Paste Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextField textField = new JTextField();
frame.add(textField, BorderLayout.NORTH);
Action actions[] = textField.getActions();
Action cutAction = findAction(actions, DefaultEditorKit.cutAction);
Action copyAction = findAction(actions, DefaultEditorKit.copyAction);
Action pasteAction = findAction(actions, DefaultEditorKit.pasteAction);
JPanel panel = new JPanel();
frame.add(panel, BorderLayout.SOUTH);
JButton cutButton = new JButton(cutAction);
cutButton.setText("Cut");
panel.add(cutButton);
JButton copyButton = new JButton(copyAction);
copyButton.setText("Copy");
panel.add(copyButton);
JButton pasteButton = new JButton(pasteAction);
pasteButton.setText("Paste");
panel.add(pasteButton);
frame.setSize(250, 250);
frame.setVisible(true);
}
public static Action findAction(Action actions[], String key) {
Hashtable<Object, Action> commands = new Hashtable<Object, Action>();
for (int i = 0; i < actions.length; i++) {
Action action = actions[i];
commands.put(action.getValue(Action.NAME), action);
}
return commands.get(key);
}
}
JTextField: getCaretPosition()
import java.awt.BorderLayout;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.text.BadLocationException;
public class MainClass {
public static void main(final String args[]) {
JFrame frame = new JFrame("Popup Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JTextField textField = new JTextField();
frame.add(textField, BorderLayout.NORTH);
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
int dotPosition = textField.getCaretPosition();
Rectangle popupLocation = null;
try {
popupLocation = textField.modelToView(dotPosition);
} catch (BadLocationException e) {
e.printStackTrace();
}
System.out.println(popupLocation);
}
};
KeyStroke keystroke =
KeyStroke.getKeyStroke(KeyEvent.VK_PERIOD, 0, false);
textField.registerKeyboardAction(actionListener, keystroke,
JComponent.WHEN_FOCUSED);
frame.setSize(250, 150);
frame.setVisible(true);
}
}
JTextField: getDocument()
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.text.AbstractDocument;
public class Main {
public static void main(String[] args) {
JFrame f = new JFrame("Text Field Elements");
JTextField tf = new JTextField(32);
tf.setText("That"s one small step for man...");
f.getContentPane().add(tf);
f.pack();
f.setVisible(true);
((AbstractDocument) tf.getDocument()).dump(System.out);
}
}
JTextField: getHorizontalVisibility()
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoundedRangeModel;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JTextField;
public class MainClass {
public static void main(String args[]) throws Exception {
JFrame frame = new JFrame("Text Slider");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final TextSlider ts = new TextSlider();
ts.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Text: " + ts.getText());
}
});
frame.add(ts, BorderLayout.NORTH);
frame.setSize(300, 100);
frame.setVisible(true);
}
}
class TextSlider extends JPanel {
private JTextField textField;
private JScrollBar scrollBar;
public TextSlider() {
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
textField = new JTextField();
scrollBar = new JScrollBar(JScrollBar.HORIZONTAL);
BoundedRangeModel brm = textField.getHorizontalVisibility();
scrollBar.setModel(brm);
add(textField);
add(scrollBar);
}
public JTextField getTextField() {
return textField;
}
public String getText() {
return textField.getText();
}
public void addActionListener(ActionListener l) {
textField.addActionListener(l);
}
public void removeActionListener(ActionListener l) {
textField.removeActionListener(l);
}
public JScrollBar getScrollBar() {
return scrollBar;
}
}
JTextField: getHorizontalVisibility() (2)
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoundedRangeModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class MainClass {
public static void main(final String args[]) {
JFrame frame = new JFrame("Offset Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new BorderLayout());
final JTextField textField = new JTextField();
panel.add(textField, BorderLayout.CENTER);
frame.add(panel, BorderLayout.NORTH);
JButton button = new JButton("Get Offset");
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
System.out.println("Offset: " + textField.getScrollOffset());
System.out.println("Visibility: " + textField.getHorizontalVisibility());
BoundedRangeModel model = textField.getHorizontalVisibility();
int extent = model.getExtent();
textField.setScrollOffset(extent);
}
};
button.addActionListener(actionListener);
frame.add(button, BorderLayout.SOUTH);
frame.setSize(250, 150);
frame.setVisible(true);
}
}
JTextField: getInputMap()
import java.awt.Event;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.text.DefaultEditorKit;
public class MainClass extends JFrame {
MainClass(String title) {
super(title);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel jp = new JPanel();
JLabel jl = new JLabel("Name:");
jp.add(jl);
JTextField jt = new JTextField(20);
jp.add(jt);
KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_B, Event.CTRL_MASK);
jt.getInputMap().put(ks, DefaultEditorKit.beepAction);
getContentPane().add(jp);
pack();
setVisible(true);
}
public static void main(String[] args) {
new MainClass("Binding Demo2");
}
}
JTextField: getKeymap()
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.text.Keymap;
public class MainClass {
public static void main(final String args[]) {
JFrame frame = new JFrame("Default Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextField textField = new JTextField();
frame.add(textField, BorderLayout.NORTH);
JPanel panel = new JPanel();
JButton defaultButton = new JButton("Default Button");
defaultButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
System.out.println(actionEvent.getActionCommand() + " selected");
}
});
panel.add(defaultButton);
JButton otherButton = new JButton("Other Button");
otherButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
System.out.println(actionEvent.getActionCommand() + " selected");
}
});
panel.add(otherButton);
frame.add(panel, BorderLayout.SOUTH);
Keymap keymap = textField.getKeymap();
KeyStroke keystroke = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, false);
keymap.removeKeyStrokeBinding(keystroke);
frame.getRootPane().setDefaultButton(defaultButton);
frame.setSize(250, 150);
frame.setVisible(true);
}
}
JTextField: getScrollOffset()
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoundedRangeModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class MainClass {
public static void main(final String args[]) {
JFrame frame = new JFrame("Offset Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new BorderLayout());
final JTextField textField = new JTextField();
panel.add(textField, BorderLayout.CENTER);
frame.add(panel, BorderLayout.NORTH);
JButton button = new JButton("Get Offset");
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
System.out.println("Offset: " + textField.getScrollOffset());
System.out.println("Visibility: " + textField.getHorizontalVisibility());
BoundedRangeModel model = textField.getHorizontalVisibility();
int extent = model.getExtent();
textField.setScrollOffset(extent);
}
};
button.addActionListener(actionListener);
frame.add(button, BorderLayout.SOUTH);
frame.setSize(250, 150);
frame.setVisible(true);
}
}
JTextField.LEADING
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class MainClass {
public static void main(final String args[]) {
JFrame frame = new JFrame("Alignment Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(0, 1));
JTextField textField = new JTextField("Left");
textField.setHorizontalAlignment(JTextField.LEFT);
frame.add(textField);
textField = new JTextField("Center");
textField.setHorizontalAlignment(JTextField.CENTER);
frame.add(textField);
textField = new JTextField("Right");
textField.setHorizontalAlignment(JTextField.RIGHT);
frame.add(textField);
textField = new JTextField("Leading");
textField.setHorizontalAlignment(JTextField.LEADING);
frame.add(textField);
textField = new JTextField("Trailing");
textField.setHorizontalAlignment(JTextField.TRAILING);
frame.add(textField);
frame.pack();
frame.setSize(250, (int) frame.getSize().getHeight());
frame.setVisible(true);
}
}
JTextField.LEFT
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class MainClass {
public static void main(final String args[]) {
JFrame frame = new JFrame("Alignment Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(0, 1));
JTextField textField = new JTextField("Left");
textField.setHorizontalAlignment(JTextField.LEFT);
frame.add(textField);
textField = new JTextField("Center");
textField.setHorizontalAlignment(JTextField.CENTER);
frame.add(textField);
textField = new JTextField("Right");
textField.setHorizontalAlignment(JTextField.RIGHT);
frame.add(textField);
textField = new JTextField("Leading");
textField.setHorizontalAlignment(JTextField.LEADING);
frame.add(textField);
textField = new JTextField("Trailing");
textField.setHorizontalAlignment(JTextField.TRAILING);
frame.add(textField);
frame.pack();
frame.setSize(250, (int) frame.getSize().getHeight());
frame.setVisible(true);
}
}
JTextField: modelToView(int pos)
import java.awt.BorderLayout;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.text.BadLocationException;
public class MainClass {
public static void main(final String args[]) {
JFrame frame = new JFrame("Popup Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JTextField textField = new JTextField();
frame.add(textField, BorderLayout.NORTH);
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
int dotPosition = textField.getCaretPosition();
Rectangle popupLocation = null;
try {
popupLocation = textField.modelToView(dotPosition);
} catch (BadLocationException e) {
e.printStackTrace();
}
System.out.println(popupLocation);
}
};
KeyStroke keystroke =
KeyStroke.getKeyStroke(KeyEvent.VK_PERIOD, 0, false);
textField.registerKeyboardAction(actionListener, keystroke,
JComponent.WHEN_FOCUSED);
frame.setSize(250, 150);
frame.setVisible(true);
}
}
JTextField: paste()
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
public class Main {
JTextField jtf = new JTextField(15);
JButton jbtnCut = new JButton("Cut");
JButton jbtnPaste = new JButton("Paste");
JButton jbtnCopy = new JButton("Copy");
public Main() {
JFrame jfrm = new JFrame("Cut, Copy, and Paste");
jfrm.setLayout(new FlowLayout());
jfrm.setSize(230, 150);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jbtnCut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent le) {
jtf.cut();
update();
}
});
jbtnPaste.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent le) {
jtf.paste();
update();
}
});
jbtnCopy.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent le) {
jtf.copy();
update();
}
});
jtf.addCaretListener(new CaretListener() {
public void caretUpdate(CaretEvent ce) {
update();
}
});
jfrm.add(jtf);
jfrm.add(jbtnCut);
jfrm.add(jbtnPaste);
jfrm.add(jbtnCopy);
jfrm.setVisible(true);
}
private void update() {
System.out.println("All text: " + jtf.getText());
if (jtf.getSelectedText() != null)
System.out.println("Selected text: " + jtf.getSelectedText());
else
System.out.println("Selected text: ");
}
public static void main(String args[]) {
new Main();
}
}
JTextField: read(Reader in, Object desc)
import java.awt.BorderLayout;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class MainClass {
public static void main(String args[]) throws Exception {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextField nameTextField = new JTextField();
frame.add(nameTextField, BorderLayout.NORTH);
FileReader reader = null;
try {
reader = new FileReader("fileName.txt");
nameTextField.read(reader, "fileName.txt");
} catch (IOException exception) {
System.err.println("Load oops");
exception.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException exception) {
System.err.println("Error closing reader");
exception.printStackTrace();
}
}
}
frame.setSize(250, 100);
frame.setVisible(true);
}
}
JTextField: registerKeyboardAction(ActionListener anAction,String aCommand,KeyStroke aKeyStroke,int aCondition)
import java.awt.BorderLayout;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.text.BadLocationException;
public class MainClass {
public static void main(final String args[]) {
JFrame frame = new JFrame("Popup Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JTextField textField = new JTextField();
frame.add(textField, BorderLayout.NORTH);
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
int dotPosition = textField.getCaretPosition();
Rectangle popupLocation = null;
try {
popupLocation = textField.modelToView(dotPosition);
} catch (BadLocationException e) {
e.printStackTrace();
}
System.out.println(popupLocation);
}
};
KeyStroke keystroke =
KeyStroke.getKeyStroke(KeyEvent.VK_PERIOD, 0, false);
textField.registerKeyboardAction(actionListener, keystroke,
JComponent.WHEN_FOCUSED);
frame.setSize(250, 150);
frame.setVisible(true);
}
}
JTextField: requestFocus()
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class Main {
public static void main(String[] argv) throws Exception {
final JTextField textfield = new JTextField(10);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
textfield.requestFocus();
}
});
}
}
JTextField: setDocument(Document doc)
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
class JTextFieldLimit extends PlainDocument {
private int limit;
JTextFieldLimit(int limit) {
super();
this.limit = limit;
}
JTextFieldLimit(int limit, boolean upper) {
super();
this.limit = limit;
}
public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException {
if (str == null)
return;
if ((getLength() + str.length()) <= limit) {
super.insertString(offset, str, attr);
}
}
}
public class Main extends JFrame {
JTextField textfield1;
JLabel label1;
public void init() {
setLayout(new FlowLayout());
label1 = new JLabel("max 10 chars");
textfield1 = new JTextField(15);
add(label1);
add(textfield1);
textfield1.setDocument(new JTextFieldLimit(10));
setSize(300,300);
setVisible(true);
}
}
JTextField: setFocusAccelerator(char aKey)
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
public class Main {
public static void main(String[] args) {
JLabel l;
JTextField t;
JButton b;
JFrame f = new JFrame("Text Accelerator");
f.add(l = new JLabel("Name:", SwingConstants.RIGHT));
l.setDisplayedMnemonic("n");
f.add(l = new JLabel("House/Street:", SwingConstants.RIGHT));
l.setDisplayedMnemonic("h");
f.add(l = new JLabel("City:", SwingConstants.RIGHT));
l.setDisplayedMnemonic("c");
f.add(l = new JLabel("State/County:", SwingConstants.RIGHT));
l.setDisplayedMnemonic("s");
f.add(l = new JLabel("Zip/Post code:", SwingConstants.RIGHT));
l.setDisplayedMnemonic("z");
f.add(l = new JLabel("Telephone:", SwingConstants.RIGHT));
l.setDisplayedMnemonic("t");
f.add(b = new JButton("Clear"));
b.setMnemonic("l");
f.add(t = new JTextField(35));
t.setFocusAccelerator("n");
f.add(t = new JTextField(35));
t.setFocusAccelerator("h");
f.add(t = new JTextField(35));
t.setFocusAccelerator("c");
f.add(t = new JTextField(35));
t.setFocusAccelerator("s");
f.add(t = new JTextField(35));
t.setFocusAccelerator("z");
f.add(t = new JTextField(35));
t.setFocusAccelerator("t");
f.add(b = new JButton("OK"));
b.setMnemonic("o");
f.pack();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}
JTextField: setHorizontalAlignment(int alignment)
import javax.swing.JTextField;
public class Main{
public static void main(String[] argv) {
JTextField textfield = new JTextField(10);
textfield.setHorizontalAlignment(JTextField.RIGHT);
}
}
JTextField: setInputVerifier(InputVerifier input)
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.InputVerifier;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;
public class MainClass {
public static void main(String args[]) throws Exception {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextField nameTextField = new JTextField();
frame.add(nameTextField, BorderLayout.NORTH);
frame.add(new JTextField(), BorderLayout.SOUTH);
InputVerifier verifier = new InputVerifier() {
public boolean verify(JComponent input) {
final JTextComponent source = (JTextComponent) input;
String text = source.getText();
if ((text.length() != 0) && !(text.equals("Exit"))) {
JOptionPane.showMessageDialog(source, "Can"t leave.", "Error Dialog",
JOptionPane.ERROR_MESSAGE);
return false;
} else {
return true;
}
}
};
nameTextField.setInputVerifier(verifier);
frame.setSize(250, 100);
frame.setVisible(true);
}
}
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.text.NavigationFilter;
import javax.swing.text.Position;
public class MainClass {
public static void main(String args[]) throws Exception {
final String START_STRING = "Start\n";
final int START_STRING_LENGTH = START_STRING.length();
JFrame frame = new JFrame("Navigation Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextArea textArea = new JTextArea(START_STRING);
textArea.setCaretPosition(START_STRING_LENGTH);
JScrollPane scrollPane = new JScrollPane(textArea);
frame.add(scrollPane, BorderLayout.CENTER);
NavigationFilter filter = new NavigationFilter() {
public void setDot(NavigationFilter.FilterBypass fb, int dot, Position.Bias bias) {
if (dot < START_STRING_LENGTH) {
fb.setDot(START_STRING_LENGTH, bias);
} else {
fb.setDot(dot, bias);
}
}
public void moveDot(NavigationFilter.FilterBypass fb, int dot, Position.Bias bias) {
if (dot < START_STRING_LENGTH) {
fb.setDot(START_STRING_LENGTH, bias);
} else {
fb.setDot(dot, bias);
}
}
};
textArea.setNavigationFilter(filter);
frame.setSize(250, 150);
frame.setVisible(true);
}
}
JTextField: setPreferredSize(Dimension preferredSize)
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Main {
public static void main(String[] args) {
JTextField tf = new JTextField("mm");
tf.setPreferredSize(tf.getPreferredSize());
tf.setText("");
JPanel pHacked = new JPanel();
pHacked.add(tf);
JPanel pStock = new JPanel();
pStock.add(new JTextField(2));
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new java.awt.GridLayout(0, 1));
frame.add(pHacked);
frame.add(pStock);
frame.setSize(150, 150);
frame.setVisible(true);
tf.requestFocus();
}
}
JTextField: setTransferHandler(TransferHandler newHandler)
/**
* Demonstrate various aspects of Swing "data transfer".
* @author Ian Darwin, http://www.darwinsys.ru
* @author Jonathan Fuerth, http://www.SQLPower.ca
*/
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.TransferHandler;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class MainClass extends JFrame {
public static void main(String[] args) {
new MainClass().setVisible(true);
}
private JTextField tf;
private JLabel l;
private JComboBox propertyComboBox;
public MainClass() {
Container cp = new Box(BoxLayout.X_AXIS);
setContentPane(cp);
JPanel firstPanel = new JPanel();
propertyComboBox = new JComboBox();
propertyComboBox.addItem("text");
propertyComboBox.addItem("font");
propertyComboBox.addItem("background");
propertyComboBox.addItem("foreground");
firstPanel.add(propertyComboBox);
cp.add(firstPanel);
cp.add(Box.createGlue());
tf = new JTextField("Hello");
tf.setForeground(Color.RED);
tf.setDragEnabled(true);
cp.add(tf);
cp.add(Box.createGlue());
l = new JLabel("Hello");
l.setBackground(Color.YELLOW);
cp.add(l);
cp.add(Box.createGlue());
JSlider stryder = new JSlider(SwingConstants.VERTICAL);
stryder.setMinimum(10);
stryder.setValue(14);
stryder.setMaximum(72);
stryder.setMajorTickSpacing(10);
stryder.setPaintTicks(true);
cp.add(stryder);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500, 300);
setMyTransferHandlers((String) propertyComboBox.getSelectedItem());
MouseListener myDragListener = new MouseAdapter() {
public void mousePressed(MouseEvent e) {
JComponent c = (JComponent) e.getSource();
TransferHandler handler = c.getTransferHandler();
handler.exportAsDrag(c, e, TransferHandler.COPY);
}
};
l.addMouseListener(myDragListener);
propertyComboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ce) {
JComboBox bx = (JComboBox) ce.getSource();
String prop = (String) bx.getSelectedItem();
setMyTransferHandlers(prop);
}
});
tf.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
JTextField jtf = (JTextField) evt.getSource();
String fontName = jtf.getText();
Font font = new Font(fontName, Font.BOLD, 18);
tf.setFont(font);
}
});
stryder.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent evt) {
JSlider sl = (JSlider) evt.getSource();
Font oldf = tf.getFont();
Font newf = oldf.deriveFont((float) sl.getValue());
tf.setFont(newf);
}
});
}
private void setMyTransferHandlers(String s) {
TransferHandler th = new TransferHandler(s);
tf.setTransferHandler(th);
l.setTransferHandler(th);
}
}
JTextField.TRAILING
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class MainClass {
public static void main(final String args[]) {
JFrame frame = new JFrame("Alignment Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(0, 1));
JTextField textField = new JTextField("Left");
textField.setHorizontalAlignment(JTextField.LEFT);
frame.add(textField);
textField = new JTextField("Center");
textField.setHorizontalAlignment(JTextField.CENTER);
frame.add(textField);
textField = new JTextField("Right");
textField.setHorizontalAlignment(JTextField.RIGHT);
frame.add(textField);
textField = new JTextField("Leading");
textField.setHorizontalAlignment(JTextField.LEADING);
frame.add(textField);
textField = new JTextField("Trailing");
textField.setHorizontalAlignment(JTextField.TRAILING);
frame.add(textField);
frame.pack();
frame.setSize(250, (int) frame.getSize().getHeight());
frame.setVisible(true);
}
}
JTextField: write(Writer out)
import java.awt.BorderLayout;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class MainClass {
public static void main(String args[]) throws Exception {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextField nameTextField = new JTextField();
frame.add(nameTextField, BorderLayout.NORTH);
FileWriter writer = null;
try {
writer = new FileWriter("filename.txt");
nameTextField.write(writer);
} catch (IOException exception) {
System.err.println("Save oops");
exception.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException exception) {
System.err.println("Error closing writer");
exception.printStackTrace();
}
}
}
frame.setSize(250, 100);
frame.setVisible(true);
}
}
new JTextField(String text)
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Main {
public static void main(String[] args) {
JTextField tf = new JTextField("mm");
tf.setPreferredSize(tf.getPreferredSize());
tf.setText("");
JPanel pHacked = new JPanel();
pHacked.add(tf);
JPanel pStock = new JPanel();
pStock.add(new JTextField(2));
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new java.awt.GridLayout(0, 1));
frame.add(pHacked);
frame.add(pStock);
frame.setSize(150, 150);
frame.setVisible(true);
tf.requestFocus();
}
}
new JTextField(String text, int columns)
import javax.swing.*;
import java.awt.*;
public class Main extends JFrame {
public Main() {
super("JTextField Test");
getContentPane().setLayout(new FlowLayout());
JTextField textField1 = new JTextField("1", 1);
JTextField textField2 = new JTextField("22", 2);
JTextField textField3 = new JTextField("333", 3);
getContentPane().add(textField1);
getContentPane().add(textField2);
getContentPane().add(textField3);
setSize(300, 170);
setVisible(true);
}
public static void main(String argv[]) {
new Main();
}
}