Java技术专题程序员

Swing系列之JTextField(单行文本框)

2017-04-08  本文已影响387人  爱撒谎的男孩

介绍

构造函数

常用的函数

  1. JTextField.CENTER
  2. JTextField.RIGHT
  3. JTextField.LEADING (the default)
  4. JTextField.TRAILING

一个简单的实例

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

class text extends JFrame {
    private JTextField textField1;
    private JTextField textField2;

    public static void main(String args[]) {
        text my = new text();
        my.setVisible(true);

    }

    public text() {
        //this.setBounds(100,100,300,200);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel panel = new JPanel(new GridLayout(2, 1));
        textField1 = new JTextField(10);
        textField2 = new JTextField();
        panel.add(textField1);
        panel.add(textField2);
        this.getContentPane().add(panel, BorderLayout.CENTER);
        this.pack();
        InputVerifier verifier = new InputVerifier() {    //添加验证方式
            @Override
            public boolean verify(JComponent input) {     //重载函数
                boolean value;
                textField1 = (JTextField) input;    //将input组件强制转化为JTextField类型的单行文本框
                return textField1.getText().equals("pass");  //判断是否输入的时pass,如果不是就会验证错误

            }
        };
        textField1.setInputVerifier(verifier);   //设置验证方式
        textField1.setHorizontalAlignment(JTextField.CENTER);   //设置水平对齐方式
        Font font = new Font("楷体", Font.BOLD + Font.ITALIC, 20);
        textField1.setFont(font);   //设置字体
        textField1.setDragEnabled(true);  //设置在单行文本框中能够拖放文本,如果为false则不能够拖放文本


    }
}

关联文本文档

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();

  }
}

说明:这里是将两个文本框相关联,这样就能达到一个文本框输入的同时,另外一个也会同时更新内容

Action Listener(动作监听机制)

输入文本后按回车即可触发

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;      //强制转换,将控件类型的comp转换成JTextFiled类型的
        try {
          Integer.parseInt(textField.getText());    //将输入的内容转化程int类型,如果输入的字符串不是十进制的话就会触发                                                          //NumberFormateException错误
          returnValue = true;
        } catch (NumberFormatException e) {   
          returnValue = false;
        }
        return returnValue;        //如果返回false的话,那么指针就会一直聚焦在此文本框中,不能移动到其他的组件上
      }
    };
    textField1.setInputVerifier(verifier);
    frame.add(textField1, BorderLayout.NORTH);
    frame.add(textField2, BorderLayout.CENTER);
    frame.setSize(300, 100);
    frame.setVisible(true);
  }
}

说明:如果返回false的话,那么指针就会一直聚焦在此文本框中,不能移动到其他的组件上

将文本框中的内容保存到文件中


import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

class Main extends JFrame {
    private JTextField textField;
    private FileWriter writer;

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

    public Main() {
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel panel = new JPanel(new BorderLayout());
        JButton button = new JButton("运行");
        JLabel label = new JLabel("name");
        textField = new JTextField();
        panel.add(label, BorderLayout.WEST);
        panel.add(textField, BorderLayout.CENTER);
        String filename = "text.txt";
        button.addActionListener(new ActionListener() {    //添加一个按钮触发装置,这里只要点击一下anniu就会将文本框中的内容输入到文件中
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    writer = new FileWriter(filename, false);   //创建一个写入文件的对象,这里的false表示不在文件的末尾添加
                    textField.write(writer);     //将单行文本中输入的内容写入到文件中
                    writer.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                    System.out.println("false");
                }
            }
        });
        panel.add(button, BorderLayout.SOUTH);
        this.getContentPane().add(panel, BorderLayout.CENTER);
        this.pack();
    }

}

说明:这里使用的是FileWriter类将内容写入到文件中,详情请看我的上一篇文章

复制、粘贴、剪切文本

这里使用的时copy()paste()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 {
  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);
  }
}

说明:这里使用的时用三个按钮监听操作,只需要按住对应的按钮就会触发机制

添加键盘监听机制


import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.HeadlessException;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
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();  //得到最初发生event的组件对象,既是文本框对象
        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);
  }
}

参考文档

本人博客

上一篇 下一篇

猜你喜欢

热点阅读