Java Swing JTextField

2018-01-09 19:23 更新

Java Swing教程 - Java Swing JTextField


JTextField可以處理一行純文本。它的構(gòu)造函數(shù)接受以下三個值的組合。

  • A string - specifies the initial text. Default to null.
  • The number of columns - specifies the width. Default to 0.
  • A Document object - specifies the model.

文檔模型是 PlainDocument 類的一個實例。

下表列出了JTextField類的構(gòu)造函數(shù)。

ID 構(gòu)造函數(shù)/說明
1 JTextField()創(chuàng)建具有初始文本,列數(shù)和文檔的默認值的JTextField。
2 JTextField(文檔文檔,字符串文本,int列)創(chuàng)建一個JTextField,其中指定的文檔作為其模型,文本作為其初始文本,列作為列數(shù)。
3 JTextField(int columns)創(chuàng)建具有指定列作為其列數(shù)的JTextField。
4 JTextField(字符串文本)創(chuàng)建具有指定文本作為其初始文本的JTextField。
5 JTextField(String text,int columns)創(chuàng)建具有指定文本作為其初始文本和列作為其列數(shù)的JTextField。
6
7

創(chuàng)建一個空的JTextField

JTextField  emptyTextField = new JTextField();

要創(chuàng)建一個初始文本為Hello的JTextField

JTextField helloTextField = new JTextField("Hello");

要創(chuàng)建一個初始文本為Hello的JTextField...

JTextField  nameTextField = new JTextField(20);


對準

默認情況下,文本對齊是左對齊。

public void setHorizontalAlignment(int alignment)方法接受一個參數(shù)

  • JTextField.LEFT
  • JTextField.CENTER
  • JTextField.RIGHT
  • JTextField.LEADING (the default)
  • JTextField.TRAILING
import java.awt.BorderLayout;
import java.awt.event.KeyEvent;
/*  w  w w  . j ava2 s.  co m*/
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class Main {
  public static void main(String args[]) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel panel = new JPanel(new BorderLayout());
    JLabel label = new JLabel("Name: ");
    label.setDisplayedMnemonic(KeyEvent.VK_N);
    JTextField textField = new JTextField();
    textField.setHorizontalAlignment(JTextField.CENTER) ;
    
    label.setLabelFor(textField);
    panel.add(label, BorderLayout.WEST);
    panel.add(textField, BorderLayout.CENTER);
    frame.add(panel, BorderLayout.NORTH);
    frame.setSize(250, 150);
    frame.setVisible(true);

  }
}


模型

以下代碼顯示如何鏡像JTextField通過與另一個JTextField共享其模型。

import java.awt.Container;
import java.awt.GridLayout;
/*from   w  ww.jav  a  2s . co m*/
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.text.Document;

public class Main extends JFrame {
  JLabel nameLabel = new JLabel("Name:");
  JLabel mirroredNameLabel = new JLabel("Mirrored:");
  JTextField name = new JTextField(20);
  JTextField mirroredName = new JTextField(20);

  public Main() {
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    this.setLayout(new GridLayout(2, 0));

    Container contentPane = this.getContentPane();
    contentPane.add(nameLabel);
    contentPane.add(name);
    contentPane.add(mirroredNameLabel);
    contentPane.add(mirroredName);

    Document nameModel = name.getDocument();
    mirroredName.setDocument(nameModel);
    
    pack();
    setVisible(true);    
  }

  public static void main(String[] args) {
    Main frame = new Main();

  }
}

以下代碼顯示如何鏡像JTextField通過與另一個JTextField共享其模型。...

下面的代碼包含一個LimitedCharDocument類,它繼承自PlainDocument類。

import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

class LimitedCharDocument extends PlainDocument {
  private int limit = 10;
  public LimitedCharDocument() {
  }
  @Override
  public void insertString(int offset, String str, AttributeSet a)
      throws BadLocationException {
    String newString = str;
    if (str != null) {
      int currentLength = this.getLength();
      int newTextLength = str.length();
      if (currentLength + newTextLength > limit) {
        newString = str.substring(0, limit - currentLength);
      }
    }

    super.insertString(offset, newString, a);
  }
}

下面的代碼包含一個LimitedCharDocument類,它繼承自PlainDocument類。...

int offset 是字符串插入JTextField的位置。

String str 是插入到JTextField中的字符串。

AttributeSet a 與插入的文本相關(guān)聯(lián)。

我們可以使用LimitedCharDocument如下:

Document tenCharDoc  = new LimitedCharDocument(10);
JTextField t1 = new JTextField(tenCharDoc, "your  name",  10);

還有一種為JTextField設置文檔的方法。 我們可以創(chuàng)建一個新類繼承自JTextField并覆蓋其createDefaultModel()方法。

createDefaultModel()方法在JTextField類中聲明為protected并返回一個PlainDocument。

要自定義JTextField,我們可以從此方法返回自定義文檔類的實例。

要自定義JTextField,我們可以從此方法返回自定義文檔類的實例。...

class TenCharTextField extends  JTextField  {
    @Override
    protected Document createDefaultModel()  {
        return new LimitedCharDocument(10);
    }
}

動作偵聽器

以下代碼顯示了如何向JTextField添加Action Listener。單擊Enter按鈕時會觸發(fā)動作偵聽器。

import java.awt.event.ActionEvent;
//from  w  w  w. ja va2s  .c o m
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 jTextField1 = new JTextField();

    jTextField1.setText("jTextField1");
    jTextField1.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(ActionEvent e) {
        System.out.println("action");
      }
    });
    frame.add(jTextField1);

    frame.setSize(300, 200);
    frame.setVisible(true);
  }

}

在聚焦橫移期間驗證輸入

以下代碼顯示如何使用InputVerifier進行驗證在焦點遍歷期間輸入。

import java.awt.BorderLayout;
import javax.swing.InputVerifier;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Main {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Verifier Sample");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JTextField textField1 = new JTextField();
    JTextField textField2 = new JTextField();
    InputVerifier verifier = new InputVerifier() {
      public boolean verify(JComponent comp) {
        boolean returnValue;
        JTextField textField = (JTextField) comp;
        try {//from w  ww .  j ava  2  s.c o m
          Integer.parseInt(textField.getText());
          returnValue = true;
        } catch (NumberFormatException e) {
          returnValue = false;
        }
        return returnValue;
      }
    };
    textField1.setInputVerifier(verifier);
    frame.add(textField1, BorderLayout.NORTH);
    frame.add(textField2, BorderLayout.CENTER);
    frame.setSize(300, 100);
    frame.setVisible(true);
  }
}

在聚焦橫移期間驗證輸入...

為了確保內(nèi)容的結(jié)尾可見,更改scrollOffset設置。

import java.awt.BorderLayout;
import java.awt.event.KeyEvent;
/* w  ww  .  j  av  a  2s .  c  o  m*/
import javax.swing.BoundedRangeModel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class Main {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Label Focus Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel panel = new JPanel(new BorderLayout());
    JLabel label = new JLabel("Name: ");
    label.setDisplayedMnemonic(KeyEvent.VK_N);
    JTextField textField = new JTextField();
    label.setLabelFor(textField);
    panel.add(label, BorderLayout.WEST);
    panel.add(textField, BorderLayout.CENTER);
    frame.add(panel, BorderLayout.NORTH);
    frame.setSize(250, 150);
    frame.setVisible(true);

    textField.setText("Loooooooooooooooooooooooooooooooooooooooooooooooooooooooong");
    BoundedRangeModel model = textField.getHorizontalVisibility();
    int extent = model.getExtent();
    textField.setScrollOffset(extent);
    System.out.println("extent:"+extent);


  }
}

輸出到文件

以下代碼顯示如何使用write()方法寫入內(nèi)容。

import java.awt.BorderLayout;
import java.awt.event.KeyEvent;
import java.io.FileWriter;
import java.io.IOException;
/*w  w w  .  ja va2 s .  c  om*/
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class Main {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Label Focus Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel panel = new JPanel(new BorderLayout());
    JLabel label = new JLabel("Name: ");
    label.setDisplayedMnemonic(KeyEvent.VK_N);
    JTextField textField = new JTextField();
    label.setLabelFor(textField);
    panel.add(label, BorderLayout.WEST);
    panel.add(textField, BorderLayout.CENTER);
    frame.add(panel, BorderLayout.NORTH);
    frame.add(new JButton("Somewhere Else"), BorderLayout.SOUTH);
    frame.setSize(250, 150);
    frame.setVisible(true);

    textField.setText("your text");
    String filename = "test.txt";

    FileWriter writer = null;
    try {
      writer = new FileWriter(filename);
      textField.write(writer);
    } catch (IOException exception) {
      System.err.println("Save oops");
    } finally {
      if (writer != null) {
        try {
          writer.close();
        } catch (IOException exception) {
          System.err.println("Error closing writer");
          exception.printStackTrace();
        }
      }
    }
  }
}

輸出到文件...

import java.awt.Container;
/*from w w w  .  j  a  v a  2s. com*/
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class DragDropText extends JFrame {

  public static void main(String[] args) {
    new DragDropText().setVisible(true);
  }

  public DragDropText() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JTextField field1 = new JTextField("Life"s a drag", 20);
    JTextField field2 = new JTextField("and then you drop", 20);
    field1.setDragEnabled(true);
    field2.setDragEnabled(true);
    Container content = getContentPane();

    content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
    content.add(field1);
    content.add(field2);

    pack();
  }
}

在JTextField中剪切,粘貼和復制

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
// w  ww. j a  v  a 2 s  .co m
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 {
  public static void main(String args[]) {
    final JTextField textField = new JTextField(15);
    JButton buttonCut = new JButton("Cut");
    JButton buttonPaste = new JButton("Paste");
    JButton buttonCopy = new JButton("Copy");

    JFrame jfrm = new JFrame("Cut, Copy, and Paste");
    jfrm.setLayout(new FlowLayout());
    jfrm.setSize(230, 150);
    jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    buttonCut.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent le) {
        textField.cut();
      }
    });

    buttonPaste.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent le) {
        textField.paste();
      }
    });

    buttonCopy.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent le) {
        textField.copy();
      }
    });

    textField.addCaretListener(new CaretListener() {
      public void caretUpdate(CaretEvent ce) {
        System.out.println("All text: " + textField.getText());
        if (textField.getSelectedText() != null)
          System.out.println("Selected text: " + textField.getSelectedText());
        else
          System.out.println("Selected text: ");
      }
    });

    jfrm.add(textField);
    jfrm.add(buttonCut);
    jfrm.add(buttonPaste);
    jfrm.add(buttonCopy);
    jfrm.setVisible(true);
  }
}

將鍵監(jiān)聽器事件處理程序添加到JTextField

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.HeadlessException;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
//from w  w w  . j  a v  a  2s  . co  m
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class Main extends JFrame {
  public Main() throws HeadlessException {
    setSize(200, 200);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLayout(new FlowLayout(FlowLayout.LEFT));

    JLabel usernameLabel = new JLabel("Username: ");
    JTextField usernameTextField = new JTextField();
    usernameTextField.setPreferredSize(new Dimension(100, 20));
    add(usernameLabel);
    add(usernameTextField);

    usernameTextField.addKeyListener(new KeyAdapter() {
      public void keyReleased(KeyEvent e) {
        JTextField textField = (JTextField) e.getSource();
        String text = textField.getText();
        textField.setText(text.toUpperCase());
      }

      public void keyTyped(KeyEvent e) {
      }

      public void keyPressed(KeyEvent e) {
      }
    });
  }

  public static void main(String[] args) {
    new Main().setVisible(true);
  }
}

將焦點設置在特定的JTextField上

import javax.swing.JTextField;
import javax.swing.SwingUtilities;
/*  w  w  w . j  a  v  a2s.c  o  m*/
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內(nèi)容,啟用或禁用JButton

import java.awt.BorderLayout;
/*  ww  w .j ava 2  s.c  o  m*/
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.Document;

public class Main {

  public Main() {
    JButton button = new JButton("foo");
    JTextField textField = new JTextField(10);
    Document document = textField.getDocument();
    document.addDocumentListener(new JButtonStateController(button));
  
    JFrame frame = new JFrame();
    frame.add(button,BorderLayout.WEST);
    frame.add(textField,BorderLayout.CENTER);
    frame.setSize(300,300);
    frame.setVisible(true);
  }

}
class JButtonStateController implements DocumentListener {
 JButton button;
  
  JButtonStateController(JButton button) {
     this.button = button ;
  }

  public void changedUpdate(DocumentEvent e) {
    disableIfEmpty(e);
  }

  public void insertUpdate(DocumentEvent e) {
    disableIfEmpty(e);
  }

  public void removeUpdate(DocumentEvent e) {
    disableIfEmpty(e);
  }

  public void disableIfEmpty(DocumentEvent e) {
    button.setEnabled(e.getDocument().getLength() > 0);
  }
}
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號