Java文本框、密码框的使用

参考文档:http://docs.oracle.com/javase/8/docs/api/index.html
1.文本框的使用

package com.Swing;
import javax.swing.*;
import java.awt.event.*;
public class TextFieldExample implements ActionListener {
    JTextField tf1, tf2, tf3;
    JButton b1, b2;

    TextFieldExample() {
        JFrame f = new JFrame();
        tf1 = new JTextField();
        tf1.setBounds(50, 50, 150, 20);
        tf2 = new JTextField();
        tf2.setBounds(50, 100, 150, 20);
        tf3 = new JTextField();
        tf3.setBounds(50, 150, 150, 20);
        tf3.setEditable(false);
        b1 = new JButton("+");
        b1.setBounds(50, 200, 50, 30);
        b2 = new JButton("-");
        b2.setBounds(120, 200, 50, 30);
        b1.addActionListener(this);
        b2.addActionListener(this);
        f.add(tf1);
        f.add(tf2);
        f.add(tf3);
        f.add(b1);
        f.add(b2);
        f.setSize(300, 300);
        f.setLocationRelativeTo(null);
        f.setLayout(null);
        f.setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
        String s1 = tf1.getText();
        String s2 = tf2.getText();
        int a = Integer.parseInt(s1);
        int b = Integer.parseInt(s2);
        int c = 0;
        if (e.getSource() == b1) {
            c = a + b;
        } else if (e.getSource() == b2) {
            c = a - b;
        }
        String result = String.valueOf(c);
        tf3.setText(result);
    }

    public static void main(String[] args) {
        new TextFieldExample();
     }
}  

结果:
Java文本框、密码框的使用_第1张图片

  1. 密码框的使用
 package com.Swing;

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

public class PasswordDemo {
    public static void main(String[] args) {
        JFrame f = new JFrame("演示");

        JLabel label = new JLabel();
        label.setBounds(20, 150, 200, 50);
        JPasswordField value = new JPasswordField();
        value.setBounds(100, 75, 100, 30);
        JLabel l1 = new JLabel("账号:");
        l1.setBounds(20, 20, 80, 30);
        JLabel l2 = new JLabel("密码:");
        l2.setBounds(20, 75, 80, 30);
        JButton b = new JButton("登录");
        b.setBounds(100, 120, 100, 30);
        JTextField text = new JTextField();
        text.setBounds(100, 20, 100, 30);
        f.add(value);
        f.add(l1);
        f.add(label);
        f.add(l2);
        f.add(b);
        f.add(text);
        f.setSize(300, 300);
        f.setLocationRelativeTo(null);
        f.setLayout(null);
        f.setVisible(true);
        b.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String data = "账号 " + text.getText();
                data += ", 密码: " + new String(value.getPassword());
                label.setText(data);
            }
        });
    }
}

结果:
Java文本框、密码框的使用_第2张图片

你可能感兴趣的:(Java-Swing)