Java6学习笔记8——利用Swing开发密码栏和文本栏

import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.Container;
import java.awt.Insets;
import java.awt.Dimension;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowAdapter;

public class FieldDemo extends JFrame implements ActionListener {
JTextField nameField;
JPasswordField passField;
public static void main(String arg[]) {
new FieldDemo();
}
public FieldDemo() {
int height;
int width;
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
} );
setLocation(250,150);
Container pane = getContentPane();
pane.setLayout(null);
Insets insets = pane.getInsets();

JLabel nameLabel = new JLabel("User name");
Dimension labelDim = nameLabel.getPreferredSize();
int x1 = insets.left + 20;
int y1 = insets.top + 20;
nameLabel.setBounds(x1,y1,labelDim.width,labelDim.height);
nameLabel.setHorizontalTextPosition(JLabel.RIGHT);
pane.add(nameLabel);

JLabel passLabel = new JLabel("Password");
int x2 = x1;
int y2 = y1 + labelDim.height + 20;
passLabel.setBounds(x2,y2,labelDim.width,labelDim.height);
passLabel.setHorizontalTextPosition(JLabel.RIGHT);
pane.add(passLabel);

nameField = new JTextField(32);
x1 += labelDim.width;
Dimension textDim = nameField.getPreferredSize();
nameField.setBounds(x1,y1,textDim.width,textDim.height);
pane.add(nameField);

passField = new JPasswordField(32);//密码框专用,没有明文回显
x2 += labelDim.width;
passField.setBounds(x2,y2,textDim.width,textDim.height);
pane.add(passField);

width = x1 + textDim.width + 20 + insets.left;

JButton button = new JButton("Login");
Dimension buttonDim = button.getPreferredSize();
int x3 = (width - buttonDim.width) / 2;
int y3 = y2 + labelDim.height + 20;
button.setBounds(x3,y3,buttonDim.width,buttonDim.height);
button.addActionListener(this);
pane.add(button);

height = y3 + buttonDim.height + 40 + insets.bottom;

setSize(width,height);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
System.out.println(nameField.getText());
char password[] = passField.getPassword();
System.out.println(password);
System.exit(0);
}
}

你可能感兴趣的:(java,swing)