JTextField可以处理一行纯文本。它的构造函数接受以下三个值的组合。
文档模型是 PlainDocument
类的一个实例。
下表列出了JTextField类的构造函数。
ID | 构造函数/说明 |
---|---|
1 | JTextField()创建具有初始文本,列数和文档的默认值的JTextField。 |
2 | JTextField(文档文档,字符串文本,int列)创建一个JTextField,其中指定的文档作为其模型,文本作为其初始文本,列作为列数。 |
3 | JTextField(int columns)创建具有指定列作为其列数的JTextField。 |
4 | JTextField(字符串文本)创建具有指定文本作为其初始文本的JTextField。 |
5 | JTextField(String text,int columns)创建具有指定文本作为其初始文本和列作为其列数的JTextField。 |
6 | |
7 |
创建一个空的JTextField
JTextField emptyTextField = new JTextField();
要创建一个初始文本为Hello的JTextField
JTextField helloTextField = new JTextField("Hello");
要创建一个初始文本为Hello的JTextField...
JTextField nameTextField = new JTextField(20);
默认情况下,文本对齐是左对齐。
public void setHorizontalAlignment(int alignment)方法接受一个参数
import java.awt.BorderLayout; import java.awt.event.KeyEvent; 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; 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
与插入的文本相关联。
我们可以使用LimitedCharDocument如下:
Document tenCharDoc = new LimitedCharDocument(10); JTextField t1 = new JTextField(tenCharDoc, "your name", 10);
还有一种为JTextField设置文档的方法。 我们可以创建一个新类继承自JTextField并覆盖其createDefaultModel()方法。
createDefaultModel()方法在JTextField类中声明为protected并返回一个PlainDocument。
要自定义JTextField,我们可以从此方法返回自定义文档类的实例。
要自定义JTextField,我们可以从此方法返回自定义文档类的实例。...
class TenCharTextField extends JTextField { @Override protected Document createDefaultModel() { return new LimitedCharDocument(10); } }
以下代码显示了如何向JTextField添加Action Listener。单击Enter按钮时会触发动作侦听器。
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); } }
为了确保内容的结尾可见,更改scrollOffset设置。
import java.awt.BorderLayout; import java.awt.event.KeyEvent; 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()方法写入内容。
import java.awt.BorderLayout; import java.awt.event.KeyEvent; import java.io.FileWriter; import java.io.IOException; 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; 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(); } }
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); } }
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); } }
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(); } }); } }
import java.awt.BorderLayout; 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); } }
Java Swing教程 -Java Swing拖放拖放(DnD)是一种在应用程序中传输数据的方法。DnD允许我们通过拖动组件并将其拖放到另一个组件上...
Java Swing教程 -JLabel JLabel 表示标签,即用于不可编辑的文本的显示区域。 JLabel 可以显示文本和图像。它甚至可以渲染HTML标...
通用CRUD封装BaseMapper接口,为Mybatis-Plus启动时自动解析实体表关系映射转换为Mybatis内部对象注入容器泛型T为任意实...
MyBatis-Plus 条件构造器-AbstractWrappernested(ConsumerParam consumer)nested(boolean condition, ConsumerParam consumer)正...