1、文本框JTextField
public class Demo extends JFrame { public Demo() { setBounds(100, 100, 200, 120); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); Container c = getContentPane(); c.setLayout(new FlowLayout()); JTextField tf = new JTextField();//创建文本框 tf.setColumns(15);//文本框长度 tf.setText("黑体,加粗,20"); tf.setFont(new Font("黑体", Font.BOLD, 20)); c.add(tf); JButton btn = new JButton("打印"); btn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println(tf.getText()); tf.setText("");//清空文本 tf.requestFocus();//获取焦点 } }); c.add(btn); setVisible(true); } public static void main(String[] args) { new Demo(); } }
2、密码框JPasswordField
public class Demo extends JFrame { public Demo() { setBounds(100, 100, 200, 100); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); Container c = getContentPane(); c.setLayout(new FlowLayout()); JPasswordField pf = new JPasswordField();//密码框 pf.setColumns(15); pf.addActionListener(new ActionListener() {//添加动作监听,回车触发 public void actionPerformed(ActionEvent e) { System.out.println(pf.getPassword()); } }); c.add(pf); setVisible(true); } public static void main(String[] args) { new Demo(); } }