- 论坛徽章:
- 0
|
请教:设置文本框中光标的位置
- import java.awt.BorderLayout;
- import java.awt.Component;
- import java.awt.HeadlessException;
- import java.awt.TextField;
- import java.awt.event.WindowAdapter;
- import java.awt.event.WindowEvent;
- import javax.swing.JFrame;
- import javax.swing.JTextArea;
- import javax.swing.JTextField;
- public class JTextFieldCursorTest extends JFrame {
- private static final String FIELD_CONTENT = "Cursor should reside at the end of line";
- /**
- * @param title
- * @throws java.awt.HeadlessException
- */
- public JTextFieldCursorTest(String title) throws HeadlessException {
- super(title);
- //uncomment 1,2 or 3 to test caret position for JTextField, TextField
- // or JtextArea
- //getContentPane().add(getJtf(), BorderLayout.NORTH); //1
- //getContentPane().add(getTf(), BorderLayout.SOUTH); //2
- getContentPane().add(getJta(), BorderLayout.CENTER); //3
- setDefaultCloseOperation(DISPOSE_ON_CLOSE);
- }
- /**
- * @return
- */
- private Component getJta() {
- JTextArea jta = new JTextArea();
- jta.setText(FIELD_CONTENT + " \n\t- JTextArea");
- jta.setCaretPosition(jta.getText().length());
- return jta;
- }
- /**
- * @return
- */
- private Component getTf() {
- final TextField tf = new TextField();
- tf.setText(FIELD_CONTENT + " - TextField");
- this.addWindowListener(new WindowAdapter() {
- public void windowOpened(WindowEvent e) {
- tf.setCaretPosition(tf.getText().length());
- }
- });
- return tf;
- }
- /**
- * @return
- */
- private Component getJtf() {
- JTextField jt = new JTextField();
- jt.setText(FIELD_CONTENT + " - JTextField");
- return jt;
- }
- public static void main(String[] args) {
- JTextFieldCursorTest jtfct = new JTextFieldCursorTest(
- "TextComponent Cursor Test");
- jtfct.setBounds(100, 100, 360, 240);
- jtfct.show();
- }
- }
复制代码 |
|