RT
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;public class LoginTest extends JFrame implements ActionListener {
JLabel labelID, labelPSW;
JTextField textID;
JPasswordField textPSW;
JButton btnLogin, btnExit;
JPanel pane; LoginTest() {
setTitle("Login");
labelID = new JLabel("用户名:", JLabel.LEFT);
labelPSW = new JLabel("密    码:", JLabel.LEFT);
textID = new JTextField("");
textPSW = new JPasswordField("");
btnLogin = new JButton("登陆");
btnExit = new JButton("退出");
GridBagLayout layout = new GridBagLayout();
getContentPane().setLayout(layout);
addComponent(layout,labelID,0,0,1,1);
addComponent(layout,textID,1,0,4,1);
addComponent(layout,labelPSW,0,1,1,1);
addComponent(layout,textPSW,1,1,4,1);
addComponent(layout,btnLogin,0,2,1,1);
addComponent(layout,btnExit,1,2,1,1);
}
public void addComponent(GridBagLayout layout,Component component,int x,int y,int w,int h){
GridBagConstraints gc = new GridBagConstraints();
gc.fill = GridBagConstraints.BOTH;
gc.gridx = x;
gc.gridy = y;
gc.gridwidth = w;
gc.gridheight = h;
gc.weightx = 100;
gc.weighty = 100;
gc.insets = new Insets(5,5,5,5);
layout.setConstraints(component, gc);
if(component instanceof JButton)
((JButton)component).addActionListener(this);
getContentPane().add(component);
} public void actionPerformed(ActionEvent e) {
JButton btn = (JButton) e.getSource();
JFrame frame = new JFrame();
String strID = textID.getText();
String strPSW = new String(textPSW.getPassword());
if (btn == btnLogin) {
if (strID.equals("")) {
JOptionPane.showMessageDialog(frame, "请输入用户名!", "提示!",
JOptionPane.YES_NO_CANCEL_OPTION);
} else if (strPSW.equals("")) {
JOptionPane.showMessageDialog(frame, "请输入密码!", "提示!",
JOptionPane.YES_NO_CANCEL_OPTION);
} else {
if (strID.equals("admin") && strPSW.equals("123456")) {
JOptionPane.showMessageDialog(frame, "登陆成功!", "提示!",
JOptionPane.YES_NO_CANCEL_OPTION);
} else {
JOptionPane.showMessageDialog(frame, "用户名或密码错误!", "错误!",
JOptionPane.ERROR_MESSAGE);
}
}
} else if (btn == btnExit) {
System.exit(0);
}
} public static void main(String args[]) {
LoginTest lt = new LoginTest();
lt.setBounds(400, 150, 220, 135);
lt.setVisible(true);
lt.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}我想让文本框力前面的标签近一点,还有按钮再小一点,这样就好看一点,但是不知道怎么弄,还请大哥们帮帮忙! 还有就是那个什么weightx,weighty不知道怎么用,也请大哥么说一下!!

解决方案 »

  1.   

    可以把textfield长度设的长一些,可以使用boxlayout好一点,按钮大小可以不用weightx,weighty设的,Dimension(a,b)就行了
      

  2.   

    Dimension(a,b)怎么用啊  
      

  3.   

    还有就是怎么在文本框里按下回车怎么跳到下一行啊 我 else if(e.getSource() == textID){
    textPSW.requestFocus();
    }
    else if(e.getSource() == textPSW){
    btnLogin.requestFocus();
    }  这么写为什么不行啊 麻烦帮我改一下!!
      

  4.   

    用GridLayout布局将分成2行2列,把那个TextFiled的长度设置长一点!