文本框
发布日期:2021-05-10 00:19:21 浏览次数:14 分类:精选文章

本文共 1954 字,大约阅读时间需要 6 分钟。

Java Swing 组件实例分析:文本框、密码框及文本域

作为Java Swing开发者,掌握基本组件的使用是构建用户友好界面关键所在。本文将详细介绍三种常用文本输入组件的使用方法及其场景应用。

文本框(Text Field)

文本框是Java Swing中最常用的输入组件之一,支持单行文本输入。创建一个简单的文本框可以通过以下步骤实现:

public class TestTextDemo01 extends JFrame {    public TestTextDemo01() {        Container container = this.getContentPane();        container.setLayout(null);        JTextField textField1 = new JTextField("hello");        JTextField textField2 = new JTextField("word", 20);        container.add(textField1, BorderLayout.NORTH);        container.add(textField2, BorderLayout.SOUTH);        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);        this.setVisible(true);        this.setBounds(100, 100, 500, 350);    }    public static void main(String[] args) {        new TestTextDemo01();    }}

密码框(Password Field)

密码框用于保护用户输入的敏感信息,支持设置星号等替代字符显示输入内容。创建一个密码框如下:

public class TestTextDemo02 extends JFrame {    public TestTextDemo02() {        Container container = this.getContentPane();        JPasswordField passwordField = new JPasswordField();        passwordField.setEchoChar('*');        container.add(passwordField);        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);        this.setVisible(true);        this.setBounds(100, 100, 500, 350);    }    public static void main(String[] args) {        new TestTextDemo02();    }}

文本域(Text Area)

文本域支持多行文本输入,适合需要长文本输入的场景。创建一个文本域如下:

public class JScrollDemo extends JFrame {    public JScrollDemo() {        Container container = this.getContentPane();        JTextArea textArea = new JTextArea(20, 50);        textArea.setText("欢迎学习");        JScrollPane scrollPane = new JScrollPane(textArea);        container.add(scrollPane);        this.setVisible(true);        this.setBounds(100, 100, 300, 350);        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);    }    public static void main(String[] args) {        new JScrollDemo();    }}

这些组件在不同的应用场景中均能发挥重要作用,理解它们的使用方法是Java Swing开发的基础。

上一篇:笔记整理HCIA
下一篇:Swing面板

发表评论

最新留言

能坚持,总会有不一样的收获!
[***.219.124.196]2025年04月28日 06时53分00秒